Click here to Skip to main content
15,892,298 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
L=[1,2,3,4,5]

print L[4:1] #prints an empty list. Can not traverse in reverse direction.

How does L[::-1] can traverse in reverse direction?

What I have tried:

Trying to understand list traversal in python by different indices/slicing.
Posted
Updated 15-Oct-18 21:55pm

1 solution

See 3. An Informal Introduction to Python — Lists[^].

[edit]
The missing start and stop values indicate that it should use the entire list. Setting a step value of -1 causes the values to be reversed, so it treats it as
Python
list[end:start:step]

However, this only works for types that have a __reversed__() method. It is just a shorthand way of calling list.reverse();.
[/edit]
 
Share this answer
 
v2
Comments
Member 13508014 16-Oct-18 4:38am    
I read the article. I still have the same doubt.
Richard MacCutchan 16-Oct-18 4:56am    
Look at the preceding sections where it explains how slices are addressed. In fact, I would suggest you work through the entire tutorial, you will learn far more than posting questions here.
Member 13508014 16-Oct-18 5:13am    
I understood the examples given there. All examples given there makes it to understand as python maintains the list as single linked list. That is why L[4:1] gives empty list, because a singly linked list can not be traversed in reverse way. But if that is the case how does L[start:end:-1] can traverse in reverse direction is what I did not understand. This is not explained in the article.
Richard MacCutchan 16-Oct-18 10:37am    
See updated solution.
Member 13508014 16-Oct-18 12:09pm    
Excellent. It clarified my doubt.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900