New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

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

Open
rgaiacs opened this Issue Jun 19, 2017 · 1 comment

Comments

Projects
None yet
2 participants
@rgaiacs
Contributor

rgaiacs commented Jun 19, 2017

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

This comment has been minimized.

Contributor

cleary3 commented Dec 13, 2017

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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment