I want to alter a copy of a list without altering the original list. My code shows that the copy is stored at a different memory address from the original. But the original list is altered along with the copy. What am I doing wrong?
original = ['Humpty', 'Dumpty'],['Jack', 'Sprat']
revised = list(original[:])
# Reverse a name on the revised list.
# Don't alter the original list.
revised[0][0],revised[0][1]=revised[0][1],revised[0][0]
print(f"\nThe original list:\t{original}\nAnd its address:\t{id(original)}")
print(f"\nThe revised list:\t{revised}\nAnd its address:\t{id(revised)}\n")
Output:
The original list: (['Dumpty', 'Humpty'], ['Jack', 'Sprat'])
And its address: 140586839997408
The revised list: [['Dumpty', 'Humpty'], ['Jack', 'Sprat']]
And its address: 140586839996848
(I'm running Python 3.7.4.)
CodePudding user response:
You need to copy the values of the inner list.
original = [['Humpty', 'Dumpty'], ['Jack', 'Sprat']]
revised = [ar[:] for ar in original]
# Reverse a name on the revised list.
# Don't alter the original list.
revised[0][0], revised[0][1] = revised[0][1], revised[0][0]
print(f"\nThe original list:\t{original}\nAnd its address:\t{id(original)}")
print(f"\nThe revised list:\t{revised}\nAnd its address:\t{id(revised)}\n")
Output:
The original list: [['Humpty', 'Dumpty'], ['Jack', 'Sprat']]
And its address: 140210727731136
The revised list: [['Dumpty', 'Humpty'], ['Jack', 'Sprat']]
And its address: 140210729012672