Search code examples
pythonpython-3.xdefaultdict

python defaultdict(list) IndexError: list assignment index out of range


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.


Solution

  • 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]