[Tutor] arrays in python

Mark Tolonen metolone+gmane at gmail.com
Sun Jun 29 07:01:53 CEST 2008


"Kirk Z Bailey" <deliberatus at verizon.net> wrote in message 
news:4866EB28.405 at verizon.net...
> Just wondering, if I can find a way to do a 2 dimensional array in python. 
> 1 dimension would be a list it would seem; for 2, I could use a list of 
> lists?
>
> Strange how I can't think of ever needing one since I discovered snake 
> charming, but so many languages do foo dimensional arrays, it would seem 
> like there ought to be a way to do it in python.

Yes, use lists of lists, but be careful constructing them:

  >>> L=[[0]*5]*5
  >>> L
  [[0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 
0, 0, 0, 0]]
  >>> L[0][0]=1
  >>> L
  [[1, 0, 0, 0, 0], [1, 0, 0, 0, 0], [1, 0, 0, 0, 0], [1, 0, 0, 0, 0], [1, 
0, 0, 0, 0]]

Oops, five references to the same list.  Changing one changes all.

  >>> L=[[0]*5 for _ in range(5)]
  >>> L
  [[0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 
0, 0, 0, 0]]
  >>> L[0][0]=1
  >>> L
  [[1, 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 
0, 0, 0, 0]]

Use a list comprehension to construct five different lists.

--Mark




More information about the Tutor mailing list