Forums

basic question about list[::-1]

Why does L[::-1] reverse the order of L ? I thought the default start index was zero so doesn't list L start at its first entry?

From docs.python.org

The slice of s from i to j with step k is defined as the sequence of items with index x = i + nk such that 0 <= n < (j-i)/k. In other words, the indices are i, i+k, i+2k, i+3k and so on, stopping when j is reached (but never including j). When k is positive, i and j are reduced to len(s) if they are greater. When k is negative, i and j are reduced to len(s) - 1 if they are greater. If i or j are omitted or None, they become “end” values (which end depends on the sign of k).* Note, k cannot be zero. If k is None, it is treated like 1.

Thanks for your reply but what is confusing me is the first colon. I thought that meant since there is no number it defaults to zero. Doesn't that mean start at the first entry (i.e., index zero) of the list? Like you said, since i is omitted it is an end value which to me means the left-most list entry. If I understand you correctly, since the step (k) is negative for some reason we jump to the right-most entry. I thought the sign of k only tells you what direction to start moving, not which end of the list to begin at.

there is only one logical way to traverse a list one step backwards each time, from the end

Sorry if I wasn't clear, but my question essentially is why does the resulting "backward' listing start with the last item since the first colon says to start at index zero, which is the first entry of the list ?!?

I realize the "-1" instructs the list to step backwards but why is it STARTING at the last entry?

Thanks for the reply, but so far nobody has addressed this point.

It is addressed in the bolded section in the post by conrad above. That explains exactly what is going on.

Glenn, Thanks for emphasizing Conrad's reply. The book I am learning Python from (Head First) did not state that a blank colon means "start at index 0 ONLY when k is not negative", but you and Conrad made that clear. Thanks again, Dan

I've tried to do a slice list and it doesn't seem to work. This is the code I did: months = ['Jan','Feb','Mar','Apr','May','Jun','Jul','Aug','Sep','oct','nov','Dec'] months[2:8]

What was the result, and what makes you think it didn't work?