0

It's been a while since I used Python, And this one I really don't get: - I make a list of strings M1 - I copy it to M2 - Then I change a "e" to "E" using re.sub in M1 - M2 is also changed!

Here's is some code for thos who are interested. It shows this behaviour on both Anaconda2 and Python 3.6.0.

import re

# Normal operation on single strings
m1 = "Hello."
m2 = m1
m1 = re.sub("e", "E", m1)
print(m1)
print(m2)
print("")

# Normal operation on one list of strings
M = ["Hello.", "Bye-bye!"]
for i in range(len(M)):
    M[i] = re.sub("e", "E", M[i])
print (M)
print("")   

# Unexpected behaviour on a copied list of strings
M1 = ["Hello.", "Bye-bye!"]
M2 = M1
for i in range(len(M1)):
    M1[i] = re.sub("e", "E", M1[i])
print(M1)
print(M2)
  • M2 = M1 does not provide a new string with same content, its just a reference to the old string. Use for example deepcopy() – Humbalan Jan 31 '17 at 07:58
  • Super! I had no idea that Python works with pointers like that. Time to read some Python theory for me I guess. – user3766450 Feb 01 '17 at 09:09

2 Answers2

1

m2 = m1 makes m2 point to the same object that m1 points to. It's like you're copying a pointer.

If you want to copy the contents, you could do something like m2 = m1[:].

Alex L
  • 1,114
  • 8
  • 11
1

m2=m1 gives you a shallow copy of m1, which is just a reference.

You need deep copy.

see https://docs.python.org/3/library/copy.html

import copy
m1 = "Hello."
m2 = copy.deepCopy(m1)
Mithilesh Gupta
  • 2,800
  • 1
  • 17
  • 17