list1=[[1,2,3],[4,5,6],[7,8,9]]
list2=[[1,2,3],[4,5,6],[7,8,9]]
while True:
list1.pop(0)
list1=list2
print(list1)
Asked
Active
Viewed 47 times
-1

Sayse
- 42,633
- 14
- 77
- 146

Codingbeginner
- 57
- 6
-
Eventually you'll run out of things to pop, what exactly is the error you're asking about? – Sayse Oct 28 '21 at 13:31
-
`list1=list2` assigns both variables to the same list object – luigigi Oct 28 '21 at 13:33
-
https://pythontutor.com/visualize.html#mode=edit if you want to visualize execution – cmgchess Oct 28 '21 at 13:36
-
but why is this happening tho,cause list2 is a different variable right? – Codingbeginner Oct 28 '21 at 13:38
-
@Codingbeginner `list1` points to the same list as `list2` so using either of those names will change the same list – Matiiss Oct 28 '21 at 13:38
-
i want to change the value of list1 to list2 tho how do i that then – Codingbeginner Oct 28 '21 at 13:41
-
it is in the answer of the duplicate questions – luigigi Oct 28 '21 at 13:42
1 Answers
1
This hapen because you pass list2
with address to list1
then when you pop from list1
you pop from list2
too, see some iteration of your code. after three run of your while True
your list1
and list2
is empty and when you pop from list1
you got an error.
>>> list1=[[1,2,3],[4,5,6],[7,8,9]]
>>> list2=[[1,2,3],[4,5,6],[7,8,9]]
>>> list1.pop(0)
[1, 2, 3]
>>> list1=list2
>>> list1.pop(0)
[1, 2, 3]
>>> list2
[[4, 5, 6], [7, 8, 9]]
If you change your code like below and use deepcopy
you don't get an error:
import copy
list1=[[1,2,3],[4,5,6],[7,8,9]]
list2=[[1,2,3],[4,5,6],[7,8,9]]
while True:
list1.pop(0)
list1=copy.deepcopy(list2)
print(list1)

I'mahdi
- 23,382
- 5
- 22
- 30
-
-
@Codingbeginner because `list1` and `list2` have same address they are one variable with different name and when you pop from `list1` you pop from `list2` – I'mahdi Oct 28 '21 at 13:39
-
1@Codingbeginner read [this](https://stackoverflow.com/a/63533055/1740577) – I'mahdi Oct 28 '21 at 13:43