Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python list multiplication: [[...]]*3 makes 3 lists which mirror each other when modified [duplicate]

Why this is happening? I don't really understand:

>>> P = [ [()]*3 ]*3 >>> P [[(), (), ()], [(), (), ()], [(), (), ()]] >>> P[0][0]=1 >>> P [[1, (), ()], [1, (), ()], [1, (), ()]] 
like image 204
KFL Avatar asked Jul 14 '11 03:07

KFL


People also ask

What happens when you multiply a list Python?

Multiply Two Python Lists Element-wise Using Numpy This means that the first element of one list is multiplied by the first element of the second list, and so on. , that allows us to multiply two arrays.

How can I multiply all items in a list together with Python?

We can use numpy. prod() from import numpy to get the multiplication of all the numbers in the list. It returns an integer or a float value depending on the multiplication result.

How do you cross multiply two lists in Python?

This is the most straight forward method to perform this task. In this, we iterate the both the list and perform multiplication of each element with other and store result in new list. This is another way in which this task can be performed. In this, we perform the task of multiplication using product().

How do you multiply three lists in Python?

To multiply lists in Python, use the zip() function. You need to pass the lists into the zip(*iterables) function to get a list of tuples that pair elements with the same position from both lists. The zip() is a built-in Python function that creates an iterator that will aggregate elements from two or more iterables.


2 Answers

You've made 3 references to the same list.

>>> a = b = [] >>> a.append(42) >>> b [42] 

You want to do this:

P = [[()] * 3 for x in range(3)] 
like image 86
Ignacio Vazquez-Abrams Avatar answered Sep 30 '22 09:09

Ignacio Vazquez-Abrams


Lists are mutable, and multiplying a list by a number doesn't copy its elements. You can try changing it to a list comprehension, so it will evaluate [()]*3 three times, creating three different lists:

P = [ [()]*3 for i in range(3) ] 
like image 20
icktoofay Avatar answered Sep 30 '22 09:09

icktoofay