0

I am trying to use defaultdict(list) as,

dict = defaultdict(list)
dict['A'][1] = [1]

or

dict['A'][1] = list([1])

I got an error,

IndexError: list assignment index out of range

if I do

dict['A'][1].append(1)

IndexError: list index out of range

I am wondering what is the issue here.

3
  • What is list in dict = defaultdict(list) ? Commented Nov 7, 2017 at 16:13
  • 2
    Hint: what you're trying to do is basically [][1] = [1]. An empty list doesn't have a 1 index to assign to. Commented Nov 7, 2017 at 16:16
  • The issue: that is not how you assign an element to an inexistent index of a list. list.append is how it's done. Commented Nov 7, 2017 at 16:17

2 Answers 2

4

There are some issues here:

  1. You're using 1 for the index value while the default list you have start at index 0.

  2. When you append, you don't need to specify the index.

  3. And finally, it's not a good idea to declare a variable with the same name as a built-in type (dict, in this case) since that would usually result in unexpected behavior later on when you would use the built-in type.

Revised, your code would be:

>>> from collections import defaultdict
>>> d = defaultdict(list)
>>> d['A'].append(1)
>>> d['A']
[1]
Sign up to request clarification or add additional context in comments.

Comments

2

Firstly, don't use dict as a name. Use something like d so you don't mask the built-in name dict.

Secondly, d['A'][1] = list([1]) tries to access the index 1 of an empty list (the value you initialize the defaultdict with) and assign to it, that's a no-no.

You are probably looking for:

d = defaultdict(list)
d['A'].append(1)

3 Comments

what if the 1 in d['A'][1], is a key and assign to it [1] as value, what should I do, so d['A'] is a nested dict.
@daiyue Then use a defaultdict(dict)
It's a key? Then why do you initialize the defaultdict with a list and not a dict?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.