swcarpentry / python-novice-inflammation

Programming with Python
http://swcarpentry.github.io/python-novice-inflammation/
Other
300 stars 780 forks source link

list functions vs list.copy() for deep copy #385

Open rgaiacs opened 7 years ago

rgaiacs commented 7 years ago

http://swcarpentry.github.io/python-novice-inflammation/03-lists/ says

If we make a list and (attempt to) copy it then modify in place, we can cause all sorts of trouble:

odds = [1, 3, 5, 7]
primes = odds
primes.append(2)
print('primes:', primes)
print('odds:', odds)
primes: [1, 3, 5, 7, 2]
odds: [1, 3, 5, 7, 2]

This is because Python stores a list in memory, and then can use multiple names to refer to the same list. If all we want to do is copy a (simple) list, we can use the list function, so we do not modify a list we did not mean to:

odds = [1, 3, 5, 7] primes = list(odds) primes.append(2) print('primes:', primes) print('odds:', odds) primes: [1, 3, 5, 7, 2] odds: [1, 3, 5, 7]

But, as explained in https://stackoverflow.com/a/17873397/1802726, list() will not create a deep copy. Should we use the solution offered at StackOverflow?

cleary3 commented 6 years ago

The lesson does mention that this method of copying a list only works for simple lists. Much more detail than that likely dives too deeply into esoteric programming concepts not appropriate for the novice programmer audience that Software Carpentry targets. Given that the lesson calls out using list() to copy simple lists, I expect that instructors can tailor their message to specific audiences and mention deep copies if it seems that a particular class is ready to dive that deep.