Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python list problem [duplicate]

Tags:

python

list

python:

m=[[0]*3]*2
for i in range(3):
    m[0][i]=1

print m

I expect that this code should print

[[1, 1, 1], [0, 0, 0]]

but it prints

[[1, 1, 1], [1, 1, 1]] 
like image 469
Luka Rahne Avatar asked Dec 24 '09 20:12

Luka Rahne


People also ask

Are duplicates allowed in list Python?

If size of list & set is equal then it means no duplicates in list. If size of list & set are different then it means yes, there are duplicates in list.

How do you avoid duplication in a list?

If you don't want duplicates, use a Set instead of a List . To convert a List to a Set you can use the following code: // list is some List of Strings Set<String> s = new HashSet<String>(list); If really necessary you can use the same construction to convert a Set back into a List .


1 Answers

This is by design. When you use multiplication on elements of a list, you are reproducing the references.

See the section "List creation shortcuts" on the Python Programming/Lists wikibook which goes into detail on the issues with list references to mutable objects.

Their recommended workaround is a list comprehension:

>>> s = [[0]*3 for i in range(2)]
>>> s
[[0, 0, 0], [0, 0, 0]]
>>> s[0][1] = 1
>>> s
[[0, 1, 0], [0, 0, 0]]
like image 98
Mark Rushakoff Avatar answered Oct 05 '22 23:10

Mark Rushakoff