Search code examples
pythonpython-3.xcollectionsdefaultdict

defaultdict appending list of list rather than list?


I am trying to use collections.defaultdict in python 3. I tried following steps in console:

>>> from collections import defaultdict
>>> l = [1,2,3,4,5]
>>> dd = defaultdict(list)
>>> dd["one"].append(l)
>>> print(dd)
defaultdict(<class 'list'>, {'one': [[1, 2, 3, 4, 5]]})

As, you can see its adding [[1, 2, 3, 4, 5]] i.e. list of list so I need two for loops to read its variables.

Why it is not appending something like [1, 2, 3, 4, 5]??

Is there something wrong with my implementation or understanding how defaultdict works? Thank you in advance


Solution

  • Is there something wrong with my implementation or understanding how defaultdict works?

    Not at all. Your code work exactly as expected. A default value of an empty list was created, and you .append a single element to that list: [1, 2, 3, 4, 5]. Actually, this isn't really related to defaultdict at all. It's perfectly fine for a list to contain a list. .appending a list to another list is not some special operation. It's the same as appending any other element such as 1 or 'hello. The entire list you .appended is consider a single element.

    If you want to add the elements of an iterable to your list, you should use list.extend instead:

    Extend the list by appending all the items from the iterable. Equivalent to a[len(a):] = iterable.

    dd["one"].extend(l)