#### [SOLVED] List of lists changes reflected across sublists unexpectedly

I needed to create a list of lists in Python, so I typed the following:

``````myList = [ * 4] * 3
``````

The list looked like this:

``````[[1, 1, 1, 1], [1, 1, 1, 1], [1, 1, 1, 1]]
``````

Then I changed one of the innermost values:

``````myList = 5
``````

Now my list looks like this:

``````[[5, 1, 1, 1], [5, 1, 1, 1], [5, 1, 1, 1]]
``````

which is not what I wanted or expected. Can someone please explain what's going on, and how to get around it? #### @Deepak Patankar 2020-06-21 11:34:38

These questions have a lot of answers, I am adding my answer to explain the same diagrammatically.

The way you created the 2D, creates a shallow list

``````    arr = [*cols]*row
``````

Instead, if you want to update the elements of the list, you should use

``````   rows, cols = (5, 5)
arr = [[0 for i in range(cols)] for j in range(rows)]

``````

Explanation:

One can create a list using :

``````   arr = *N
``````

or

``````   arr = [0 for i in range(N)]
``````

In the first case all the indices of the array point to the same integer object and when you assign a value to a particular index, a new int object is created, for eg `arr = 5` creates Now let us see what happens when we create a list of list, in this case, all the elements of our top list will point to the same list And if you update the value of any index a new int object will be created. But since all the top-level list indexes are pointing at the same list, all the rows will look the same. And you will get the feeling that updating an element is updating all the elements in that column. Credits: Thanks to Pranav Devarakonda for the easy explanation here #### @jerrymouse 2017-04-06 05:36:57

`myList = [*4] * 3` creates one list object `[1,1,1,1]` in memory and copies its reference 3 times over. This is equivalent to `obj = [1,1,1,1]; myList = [obj]*3`. Any modification to `obj` will be reflected at three places, wherever `obj` is referenced in the list. The right statement would be:

``````myList = [*4 for _ in range(3)]
``````

or

``````myList = [[1 for __ in range(4)] for _ in range(3)]
``````

Important thing to note here is that `*` operator is mostly used to create a list of literals. Although `1` is immutable, `obj =*4` will still create a list of `1` repeated 4 times over to form `[1,1,1,1]`. But if any reference to an immutable object is made, the object is overwritten with a new one.

This means if we do `obj=42`, then `obj` will become `[1,42,1,1]` not `[42,42,42,42]` as some may assume. This can also be verified:

``````>>> myList = *4
>>> myList
[1, 1, 1, 1]

>>> id(myList)
4522139440
>>> id(myList) # Same as myList
4522139440
``````

``````>>> myList = 42 # Since myList is immutable, this operation overwrites myList with a new object changing its id.
>>> myList
[1, 42, 1, 1]

>>> id(myList)
4522139440
>>> id(myList) # id changed
4522140752
>>> id(myList) # id still same as myList, still referring to value `1`.
4522139440
`````` #### @Martijn Pieters 2018-07-25 15:52:05

It's not about literals. `obj = 42` replaces the reference at index `2`, as opposed to mutating the object referenced by that index, which is what `myList = ...` does (`myList` is a list, and the assigment alters the reference at index 0 in tha list). Of course, integers are not mutable, but plenty of object types are. And note that the `[....]` list display notation is also a form of literal syntax! Don't confuse compound (such as lists) and scalar objects (such as integers), with mutable vs. immutable objects. When you write `[x]*3` you get, essentially, the list `[x, x, x]`. That is, a list with 3 references to the same `x`. When you then modify this single `x` it is visible via all three references to it:

``````x =  * 4
l = [x] * 3
print(f"id(x): {id(x)}")
# id(x): 140560897920048
print(
f"id(l): {id(l)}\n"
f"id(l): {id(l)}\n"
f"id(l): {id(l)}"
)
# id(l): 140560897920048
# id(l): 140560897920048
# id(l): 140560897920048

x = 42
print(f"x: {x}")
# x: [42, 1, 1, 1]
print(f"l: {l}")
# l: [[42, 1, 1, 1], [42, 1, 1, 1], [42, 1, 1, 1]]
``````

To fix it, you need to make sure that you create a new list at each position. One way to do it is

``````[*4 for _ in range(3)]
``````

which will reevaluate `*4` each time instead of evaluating it once and making 3 references to 1 list.

You might wonder why `*` can't make independent objects the way the list comprehension does. That's because the multiplication operator `*` operates on objects, without seeing expressions. When you use `*` to multiply `[ * 4]` by 3, `*` only sees the 1-element list `[ * 4]` evaluates to, not the `[ * 4` expression text. `*` has no idea how to make copies of that element, no idea how to reevaluate `[ * 4]`, and no idea you even want copies, and in general, there might not even be a way to copy the element.

The only option `*` has is to make new references to the existing sublist instead of trying to make new sublists. Anything else would be inconsistent or require major redesigning of fundamental language design decisions.

In contrast, a list comprehension reevaluates the element expression on every iteration. `[ * 4 for n in range(3)]` reevaluates ` * 4` every time for the same reason `[x**2 for x in range(3)]` reevaluates `x**2` every time. Every evaluation of ` * 4` generates a new list, so the list comprehension does what you wanted.

Incidentally, ` * 4` also doesn't copy the elements of ``, but that doesn't matter, since integers are immutable. You can't do something like `1.value = 2` and turn a 1 into a 2. #### @Allanqunzi 2015-05-22 00:16:41

I am surprised that no body points out that, the answer here is misleading. `[x]*3` store 3 references like `[x, x, x]` is only right when `x` is mutable. This does't work for e.g. `a=*3`, where after `a=5`, `a=[5,4,4].` Technically, it's still correct. `*3` is essentially equivalent to `x = 4; [x, x, x]`. It's true, though, that this will never cause any problem since `4` is immutable. Also, your other example isn't really a different case. `a = [x]*3; a = 5` won't cause problems even if `x` is mutable, since you're not modifying `x`, only modifying `a`. I wouldn't describe my answer as misleading or incorrect - you just can't shoot yourself in the foot if you're dealing with immutable objects. #### @timgeb 2016-04-17 18:08:26

@Allanqunzi you are wrong. Do `x = 1000; lst = [x]*2; lst is lst` -> `True`. Python does not distinguish between mutable and immutable objects here whatsoever. #### @PierreBdR 2008-10-27 15:07:02

Actually, this is exactly what you would expect. Let's decompose what is happening here:

You write

``````lst = [ * 4] * 3
``````

This is equivalent to:

``````lst1 = *4
lst = [lst1]*3
``````

This means `lst` is a list with 3 elements all pointing to `lst1`. This means the two following lines are equivalent:

``````lst = 5
lst1 = 5
``````

As `lst` is nothing but `lst1`.

To obtain the desired behavior, you can use list comprehension:

``````lst = [ *4 for n in range(3) ] #python 3
lst = [ *4 for n in xrange(3) ] #python 2
``````

In this case, the expression is re-evaluated for each n, leading to a different list. #### @Sergiy Kolodyazhnyy 2017-05-17 07:08:16

Just a small addition to the nice answer here: it's evident that you're dealing with same object if you do `id(lst)` and `id(lst)` or even `id(lst)` and `id(lst)` #### @ouxiaogu 2019-08-09 08:37:56

@spelchekr from Python list multiplication: [[...]]*3 makes 3 lists which mirror each other when modified and I had the same question about "Why does only the outer *3 create more references while the inner one doesn't? Why isn't it all 1s?"

``````li =  * 3
print([id(v) for v in li]) # [140724141863728, 140724141863728, 140724141863728]
li = 1
print([id(v) for v in li]) # [140724141863760, 140724141863728, 140724141863728]
print(id(0)) # 140724141863728
print(id(1)) # 140724141863760
print(li) # [1, 0, 0]

ma = [*3] * 3 # mainly discuss inner & outer *3 here
print([id(li) for li in ma]) # [1987013355080, 1987013355080, 1987013355080]
ma = 1
print([id(li) for li in ma]) # [1987013355080, 1987013355080, 1987013355080]
print(ma) # [[1, 0, 0], [1, 0, 0], [1, 0, 0]]
``````

Here is my explanation after trying the code above:

• The inner `*3` also creates references, but it's references are immutable, something like `[&0, &0, &0]`, then when to change `li`, you can't change any underlying reference of const int `0`, so you can just change the reference address into the new one `&1`;
• while `ma=[&li, &li, &li]` and `li` is mutable, so when you call `ma=1`, ma is equally to `&li`, so all the `&li` instances will change its 1st address into `&1`. #### @Kasravnd 2015-06-17 17:08:52

Alongside the accepted answer that explained the problem correctly, within your list comprehension, if You are using python-2.x use `xrange()` that returns a generator which is more efficient (`range()` in python 3 does the same job) `_` instead of the throwaway variable `n`:

``````[*4 for _ in xrange(3)]      # and in python3 [*4 for _ in range(3)]
``````

Also, as a much more Pythonic way you can use `itertools.repeat()` to create an iterator object of repeated elements :

``````>>> a=list(repeat(1,4))
[1, 1, 1, 1]
>>> a=5
>>> a
[5, 1, 1, 1]
``````

P.S. Using numpy, if you only want to create an array of ones or zeroes you can use `np.ones` and `np.zeros` and/or for other number use `np.repeat()`:

``````In : import numpy as np

In :

In : np.ones(4)
Out: array([ 1.,  1.,  1.,  1.])

In : np.ones((4, 2))
Out:
array([[ 1.,  1.],
[ 1.,  1.],
[ 1.,  1.],
[ 1.,  1.]])

In : np.zeros((4, 2))
Out:
array([[ 0.,  0.],
[ 0.,  0.],
[ 0.,  0.],
[ 0.,  0.]])

In : np.repeat(, 10)
Out: array([7, 7, 7, 7, 7, 7, 7, 7, 7, 7])
`````` ``````[ * 4] * 3
``````

or even:

``````[[1, 1, 1, 1]] * 3
``````

Creates a list that references the internal `[1,1,1,1]` 3 times - not three copies of the inner list, so any time you modify the list (in any position), you'll see the change three times.

It's the same as this example:

``````>>> inner = [1,1,1,1]
>>> outer = [inner]*3
>>> outer
[[1, 1, 1, 1], [1, 1, 1, 1], [1, 1, 1, 1]]
>>> inner = 5
>>> outer
[[5, 1, 1, 1], [5, 1, 1, 1], [5, 1, 1, 1]]
``````

where it's probably a little less surprising. You can use the "is" operator to discover this. ls is ls returns True. Trying to explain it more descriptively,

Operation 1:

``````x = [[0, 0], [0, 0]]
print(type(x)) # <class 'list'>
print(x) # [[0, 0], [0, 0]]

x = 1
print(x) # [[1, 0], [0, 0]]
``````

Operation 2:

``````y = [ * 2] * 2
print(type(y)) # <class 'list'>
print(y) # [[0, 0], [0, 0]]

y = 1
print(y) # [[1, 0], [1, 0]]
``````

Noticed why doesn't modifying the first element of the first list didn't modify the second element of each list? That's because ` * 2` really is a list of two numbers, and a reference to 0 cannot be modified.

If you want to create clone copies, try Operation 3:

``````import copy
y =  * 2
print(y)   # [0, 0]

y = [y, copy.deepcopy(y)]
print(y) # [[0, 0], [0, 0]]

y = 1
print(y) # [[1, 0], [0, 0]]
``````

another interesting way to create clone copies, Operation 4:

``````import copy
y =  * 2
print(y) # [0, 0]

y = [copy.deepcopy(y) for num in range(1,5)]
print(y) # [[0, 0], [0, 0], [0, 0], [0, 0]]

y = 5
print(y) # [[5, 0], [0, 0], [0, 0], [0, 0]]
`````` #### @Anand Tripathi 2016-07-15 13:48:36

By using the inbuilt list function you can do like this

``````a
out:[[1, 1, 1, 1], [1, 1, 1, 1], [1, 1, 1, 1]]
#Displaying the list

a.remove(a)
out:[[1, 1, 1, 1], [1, 1, 1, 1]]
# Removed the first element of the list in which you want altered number

a.append([5,1,1,1])
out:[[1, 1, 1, 1], [1, 1, 1, 1], [5, 1, 1, 1]]
# append the element in the list but the appended element as you can see is appended in last but you want that in starting

a.reverse()
out:[[5, 1, 1, 1], [1, 1, 1, 1], [1, 1, 1, 1]]
#So at last reverse the whole list to get the desired list
`````` #### @U10-Forward 2018-10-19 05:29:03

Note, fourth step can be dropped if you make second step: `a.insert(0,[5,1,1,1])` #### @Neeraj Komuravalli 2016-06-14 06:36:52

In simple words this is happening because in python everything works by reference, so when you create a list of list that way you basically end up with such problems.

To solve your issue you can do either one of them: 1. Use numpy array documentation for numpy.empty 2. Append the list as you get to a list. 3. You can also use dictionary if you want #### @awulll 2016-04-24 13:31:04

I guess everybody explain what is happening. I suggest one way to solve it:

`myList = [[1 for i in range(4)] for j in range(3)]`

``````myList = 5
``````

`print myList`

And then you have:

``````[[5, 1, 1, 1], [1, 1, 1, 1], [1, 1, 1, 1]]
`````` #### @Zbyněk Winkler 2016-04-06 13:40:43

Python containers contain references to other objects. See this example:

``````>>> a = []
>>> b = [a]
>>> b
[[]]
>>> a.append(1)
>>> b
[]
``````

In this `b` is a list that contains one item that is a reference to list `a`. The list `a` is mutable.

The multiplication of a list by an integer is equivalent to adding the list to itself multiple times (see common sequence operations). So continuing with the example:

``````>>> c = b + b
>>> c
[, ]
>>>
>>> a = 2
>>> c
[, ]
``````

We can see that the list `c` now contains two references to list `a` which is equivalent to `c = b * 2`.

Python FAQ also contains explanation of this behavior: How do I create a multidimensional list? #### @bagrat 2015-06-10 14:38:24

Let us rewrite your code in the following way:

``````x = 1
y = [x]
z = y * 4

myList = [z] * 3
``````

Then having this, run the following code to make everything more clear. What the code does is basically print the `id`s of the obtained objects, which

Return the “identity” of an object

and will help us identify them and analyse what happens:

``````print("myList:")
for i, subList in enumerate(myList):
print("\t[{}]: {}".format(i, id(subList)))
for j, elem in enumerate(subList):
print("\t\t[{}]: {}".format(j, id(elem)))
``````

And you will get the following output:

``````x: 1
y: 
z: [1, 1, 1, 1]
myList:
: 4300763792
: 4298171528
: 4298171528
: 4298171528
: 4298171528
: 4300763792
: 4298171528
: 4298171528
: 4298171528
: 4298171528
: 4300763792
: 4298171528
: 4298171528
: 4298171528
: 4298171528
``````

So now let us go step-by-step. You have `x` which is `1`, and a single element list `y` containing `x`. Your first step is `y * 4` which will get you a new list `z`, which is basically `[x, x, x, x]`, i.e. it creates a new list which will have 4 elements, which are references to the initial `x` object. The net step is pretty similar. You basically do `z * 3`, which is `[[x, x, x, x]] * 3` and returns `[[x, x, x, x], [x, x, x, x], [x, x, x, x]]`, for the same reason as for the first step. ``````size = 3
matrix_surprise = [ * size] * size
matrix = [*size for i in range(size)]
`````` Live Python Tutor Visualize #### @Ahmed Mohamed 2017-07-01 17:55:18

So, why if we write matrix= [[x] * 2] doesn't make 2 elemnts for the same object like the example you describe, it seems to be the same concept, what am i missing? @AhmedMohamed Indeed it does make a list with two elements of the exact same object that `x` refers to. If you make a globally unique object with `x = object()` and then make `matrix = [[x] * 2]` these does come as true: `matrix is matrix` #### @Ahmed Mohamed 2017-07-02 13:31:54

@nadrimajstor so why the change in matrix doesn't affect matrix like the example above with 2d matrix. @AhmedMohamed Surprise come when you make a "copy" of mutable sequence (in our example it is a `list`) so if a `row = [x] * 2` than a `matrix = [row] * 2` where both rows are exactly the same object, and now changes to one row `matrix = y` suddenly reflect in the other one `(matrix is matrix) == True` @AhmedMohamed Take a look at Ned Batchelder - Facts and Myths about Python names and values as it might offer a better explanation. :)

### [SOLVED] How do I check if a list is empty?

• 2008-09-10 06:20:11
• Ray
• 3090518 View
• 3233 Score
• Tags:   python list

### [SOLVED] Finding the index of an item in a list

• 2008-10-07 01:39:38
• Eugene M
• 4090083 View
• 3327 Score
• Tags:   python list indexing