"Kirk Z Bailey" <[EMAIL PROTECTED]> wrote in message
news:[EMAIL PROTECTED]
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
_______________________________________________
Tutor maillist - [email protected]
http://mail.python.org/mailman/listinfo/tutor