3 ms·
reversed_list = list(reversed(orig_list)) This works too, and IS more readable. But this doesn't work for a string for example. I didn't stay to replace ALL s
by henryprecheur 18y ago
reversed_list = list(reversed(orig_list))
This works too, and IS more readable. But this doesn't work for a string for example.
I didn't stay to replace ALL slices with list(). Of course this wont work all the time. For instance [:] has nice properties like conserving the sequence type:
>>> (1, 2, 3)[:]
(1, 2, 3)
>>> [1, 2, 3][:]
[1, 2, 3]
This is not possible if you call list(), or tuple() directly.
Slice is a feature that requires more "cleverness" from the programmer and more brain power from the guy reading the code.
To cite Dijkstra:
"[The competent programmer] avoids clever tricks like the plague."
If list() make your code clearer, use it. The goal is to write a working program with clear and readable code, not to show off with you mastery of slices.
- anewaccountname 18y agoGive me one example where you would ever want a copy of a tuple rather than another reference to it.
- henryprecheur 18y agoThat wasn't my point. My point was that [:] conserves the type of sequence. Also [:] returns a reference to the existing tuple instead of a copy: >>> a = (1, 2, 3) >>> id(a) 3081276268L >>> id(a[:]) 3081276268L