Display the list in reverse order in python by R4R Team

example -

let we have a list in python -
l=[1,2,3,4,5,"Mytext"]

we want to display this list in reverse order like
["Mytext",5,4,3,2,1]

program -

l=[1,2,3,4,5,"Mytext"]
print("Original list is - ")
print(l)
#first method
print("List in reverse order by first method")
length=len(l)
for i in range(length):
print(l[length-1-i],end=",")

#second method
print("nList in reverse order by second method")
print(l[::-1])


output -

Original list is -
[1, 2, 3, 4, 5, 'Mytext']
List in reverse order by first method
Mytext,5,4,3,2,1,
List in reverse order by second method
['Mytext', 5, 4, 3, 2, 1]


-In this program, first method traverse the list in reverse order using for loop - But in second method we use slicing method l[::-1] represent that 0:len(l):-1 and -1 is used for back traversing.


Leave a Comment:
Search
Categories
R4R Team
R4Rin Top Tutorials are Core Java,Hibernate ,Spring,Sturts.The content on R4R.in website is done by expert team not only with the help of books but along with the strong professional knowledge in all context like coding,designing, marketing,etc!