-3
my_list = [1, 2]
print my_list[0]

1

x = my_list[0]
x += 2

now 'x' equals 3 and my_list[0] also equals 3. How can I preserve my list elements so they remain unchanged?

tanzola
  • 79
  • 1
  • 7
  • 7
    Your code works as expected: the list in unchanged. The list would change if elements within it was mutable objects (like others lists for example). Then you should import and call `x = copy.copy(my_list[0])` to prevent changes to affect the list. – Delgan Nov 18 '15 at 22:39

1 Answers1

1

You can slice it:

new_list = old_list[:]

or

import copy
new_list = copy.copy(old_list)

If this helped please voted up & marked “accepted”

Anonymous
  • 142
  • 1
  • 11