1

Any help will be greatly appreciated!!!

res = []
s = [1,2,3,4,5,6]
s.pop() 
res.append(s)
print res
s.pop()                                                                                  
res.append(s)
print res

The above python code gives the following result

[[1, 2, 3, 4, 5]]
[[1, 2, 3, 4], [1, 2, 3, 4]]

I don't understand why pop on s will affect res. I mean the print result should be

[[1,2,3,4,5]]
[[1,2,3,4,5],[1,2,3,4]]
Bhargav Rao
  • 50,140
  • 28
  • 121
  • 140
n00d1es
  • 33
  • 3

2 Answers2

0

Every value in Python is a reference (pointer) to an object. Assignment always copies the value (which is a pointer); two such pointers can thus point to the same object.

To get the needed result you need to copy the initial list:

res = []
s = [1,2,3,4,5,6]
s.pop()
res.append(s[:])
print(res)
s.pop()
res.append(s[:])
print(res)

The same can be done using list.copy() function:

...
res.append(s.copy())
...

The output:

[[1, 2, 3, 4, 5]]
[[1, 2, 3, 4, 5], [1, 2, 3, 4]]
RomanPerekhrest
  • 88,541
  • 4
  • 65
  • 105
0

This is OK - because res will hold the same reference as s(to the same object- in this case the array).

To solve this problem use this:

res = []
s = [1,2,3,4,5,6]
s.pop()
res.append(list(s))
print res
s.pop()
res.append(list(s))
print res

also take a look at :

How to clone or copy a list?

python: Appending a dictionary to a list - I see a pointer like behavior

Community
  • 1
  • 1
Dozon Higgs
  • 473
  • 2
  • 5