Reversed takes a list and reverses it.
The slicing notation iterates over the list and returns a new one.
When you call reversed
on the slice (with or without stepping) of a list, the slice is created first, and then reversed.
For example, newL = reversed(L[0:len(L):2])
is the same as:
M = L[0:len(L):2]
newL = reversed(M)
Thus, when you say reversed(L[0:len(L)-1:2])
, reversed is called on a list containing every other element in L, starting with the first, and excluding the last.
As a side note, L[::2]
is the same as L[0:len(L):2]
, and L[:-1:2]
is the same as L[0:len(L)-1:2]
. Also, L[::-1]
is L
in reverse order.
This notation is very powerful.
If you want a checkio([5, 8, 13, 27, 14])
to return [14, 13, 5, 27, 8]
, then here are a few ways to do it:
>>> L = [5, 8, 13, 27, 14]
>>> L[::-2] + L[-2::-2]
[14, 13, 5, 27, 8]
>>> L = [5, 8, 13, 27, 14]
>>> list(reversed(L))[::2] + list(reversed(L))[1::2]
[14, 13, 5, 27, 8]
>>> L = [5, 8, 13, 27, 14]
>>> list(itertools.chain(itertools.islice(reversed(L), 0, len(L), 2), itertools.islice(reversed(L), 1, len(L), 2)))
[14, 13, 5, 27, 8]
Hope this helps