Skip to content

Comment on Python: copying a list the right wayparent

Comments

Let's look at the line:

    list1 = list2[:]
That line means "list1 is a list that has all the elements of list2", not "list1 is a new list that has all the elements of list2". It just happens that the implementation of slices in the python interpreter creates a new list for a slice. You may say it is 'obvious' that it works like that, in python, I will agree with you. You might not be able to say the same thing for other languages, especially if you haven't used them before.

The problem is, even with a simple knowledge of slices, someone reading your code may not realise that list1 is actually a new list; you are depending upon a side-effect of the language. If you used the Copy module, or even the list constructor, it would have been much clearer that list1 is a new list. This increases readability, which is very important if other people, or even yourself in the future re-read the code. Personally, I prefer readability in really long programs, and it isn't like you're programming C on an embedded device here.

AboutSource Built by g1lg1l

Hackerly is an independent reader for Hacker News, built on the public HN API. Not affiliated with Y Combinator.