April 12, 2019

Using Python's list()

  —Using Python's list() function properly.

Got burned by a bug in a Python program. Forgot to copy a list and instead just assigned it a new name.

a = [ 1, 2 ]
b = a
b.pop(0)
b.append(3)
print a==b # Prints True!

print a # Prints [2, 3]
print b # Prints [2, 3]

To create a copy of a, I should have wrote b=list(a).

a = [ 1, 2 ]
b = list(a)
b.pop(0)
b.append(3)
print a==b # Prints False.

print a # Prints [1, 2]
print b # Prints [2, 3]

Bummer.

Found an article that explains this well. Python: copying a list the right way.

comments powered by Disqus