2D List

Ian Kelly ian.g.kelly at gmail.com
Tue Oct 12 12:46:44 EDT 2010


On Mon, Oct 11, 2010 at 1:44 PM, Tom Pacheco <tomslists at netp.org> wrote:

> your creating a 1d list
>
> this creates a 2d list
> a=[[[]]*5
>
>
> >>> [0]*5
> [0, 0, 0, 0, 0]
> >>> [[]]*5
> [[], [], [], [], []]
>

Don't do this.  This actually just creates a list containing the same empty
list 5 times:

>>> a = [[]] * 5
>>> a
[[], [], [], [], []]
>>> a[0].append(1)
>>> a
[[1], [1], [1], [1], [1]]
>>> a[1][0] = 2
>>> a
[[2], [2], [2], [2], [2]]

Chris gave a correct way to create a list of lists, using a list
comprehension.

Cheers,
Ian
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-list/attachments/20101012/73be2b56/attachment-0001.html>


More information about the Python-list mailing list