Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

2D list has weird behavor when trying to modify a single value [duplicate]

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?

like image 861
Brian Avatar asked Apr 29 '10 17:04

Brian


People also ask

What is the use of 2D list in Python?

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.

Can a list be 2 dimensional Python?

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.


1 Answers

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]] 
like image 74
Mark Byers Avatar answered Sep 29 '22 14:09

Mark Byers