0

I started recently Python Language and i have a problem about lists. I was surprised not to find what i was looking for by searching on Google, I guess i couldn't explain with the right words because english isn't my native language. Here's my problem:

When i create a list and i want to modify it but i want to keep the last value, I don't know how to do. I thought that i could save my list in a second list, but when i modify the other list, it doesn't stay constant.

list1=[1,2,3,4]
list2=list1
list1.append(5)
print(list2)

For exemple, here, I thought that my list2 will stay constant but no, it is synchronised to the list1 and when I print(list2), the 5 that i added in list1 appears.

I really don't know how to solve this problem, if someone could help me it would be very cool, thanks !

Pho Konte
  • 21
  • 3
  • 1
    You may find https://nedbatchelder.com/text/names1.html helpful. There is an example on it that is almost your exact code. – scomes Nov 07 '18 at 20:40
  • @clearshot66 answered the question, but I'd suggest learning how lists are stored in memory. – Tim Nov 07 '18 at 20:41

1 Answers1

1

Try this:

# Set list 1
list1 = [1,2,3,4]
# Make a copy of list one as it sits, not assigning list1 to list 2, 
# Previously, anything done to list1 will happen with list2 since list2 is 
# assigned AS list 1
list2 = list1.copy()
# Add your 5
list1.append(5)
print(list1)
print(list2)
clearshot66
  • 2,292
  • 1
  • 8
  • 17