how to make a nested list

Vlastimil Brom vlastimil.brom at gmail.com
Thu Sep 15 18:02:10 EDT 2011


2011/9/15 Stef Mientki <stef.mientki at gmail.com>:
> hello,
>
> I need a nested list, like this
>
>>>> A= [ [None,None], [None,None], [None, None] ]
>>>> A[2][0] =77
>>>> A
> [[None, None], [None, None], [77, None]]
> ...
>
> thanks,
> Stef
> --
> http://mail.python.org/mailman/listinfo/python-list
>

Besides the above sugestions to correct the nested list approach,
if you need to set and access the data at the given "coordinates" you
could also use a nested defaultdict, which doesn't need to be
pre-filled before setting, e.g.:

>>> from collections import defaultdict as dd
>>> def dd_dd():
...     return dd(dd)
...
>>> dd_matrix = dd(dd_dd)
>>>
>>> dd_matrix[2][0] = 77
>>> dd_matrix[2][0]
77
>>> dd_matrix
defaultdict(<function dd_dd at 0x04E5B8B0>, {2: defaultdict(<type
'collections.defaultdict'>, {0: 77})})
>>>

However, the nested list are concise enough, I guess.

Regards,
   vbr



More information about the Python-list mailing list