r/Python • • Jun 23 '14

Writing better python code

https://gist.github.com/kracekumar/09a60ec75a4de19b346e
143 Upvotes

126 comments sorted by

View all comments

7

u/oconnor663 Jun 23 '14 edited Jun 23 '14

Is foo[:] really the Pythonic way to copy a list?

Edit: In Python 3, lists have their own .copy() method.

2

u/metaphorm Jun 23 '14

foo[:] is a totally respectable way to copy a list. it looks a little funny if you've never seen it, but it has the right semantics and does exactly what you would expect when slicing "from the beginning to the end". it does, however, rely on the programmer knowing that list slices produce copies.

2

u/zahlman the heretic Jun 23 '14

I dislike it because it's conceptually roundabout. "A list containing elements of x, from the beginning to the end" is similarly awkward in English compared to "a copy of x", or even "a list of the contents of x". Even if the analogous Python is terse.

2

u/metaphorm Jun 23 '14

I understand your point. I disagree that its conceptually roundabout. Once you understand that the slice operator really means "return a copy of this section of the list" it seems really natural.