Possible Duplicate:
Unexpected feature in a Python list of lists
So I am relatively new to Python and I am having trouble working with 2D Lists.
Here's my code:
data = [[None]*5]*5 data[0][0] = 'Cell A1' print data
and here is the output (formatted for readability):
[['Cell A1', None, None, None, None], ['Cell A1', None, None, None, None], ['Cell A1', None, None, None, None], ['Cell A1', None, None, None, None], ['Cell A1', None, None, None, None]]
Why does every row get assigned the value?
The list is a data structure that is used to store multiple values linearly. However, there exist two-dimensional data. A multi-dimensional data structure is needed to keep such type of data. In Python, a two-dimensional list is an important data structure.
Python provides many ways to create 2-dimensional lists/arrays. However one must know the differences between these ways because they can create complications in code that can be very difficult to trace out.
This makes a list with five references to the same list:
data = [[None]*5]*5
Use something like this instead which creates five separate lists:
>>> data = [[None]*5 for _ in range(5)]
Now it does what you expect:
>>> data[0][0] = 'Cell A1' >>> print data [['Cell A1', None, None, None, None], [None, None, None, None, None], [None, None, None, None, None], [None, None, None, None, None], [None, None, None, None, None]]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With