How to reverse list in python?
There are a few techniques to reverse a list. We will study them here.
Using reverse()
The reverse() reverses the items of the list. This is done “in place”, i.e., it does not create a new list. The syntax to use reverse method is:
list.reverse()
Takes no argument, returns no list; reverses the “in place” and does not return anything.
t1=['a', 'b', 'c', 'd', 'e'] t1.reverse() print(t1)
output- ['e', 'd','c','b', 'a']
Using reversed()
If we need to access individual elements of a list in the reverse order, it’s better to use reversed()
function.
t1=['blog', 'python', 'Cpython', 'pythonpoint'] for s in reversed(t1): print(s)
output- pythonpoint Cpyhton python blog
Using slicing technique
t1=['blog', 'python', 'Cpython', 'pythonpoint'] reversed_list = t1[::-1] print(reversed_list)
output=['pythonpoint', 'Cpython', 'python ', 'blog']
These are some techniques that we used to reverse a string.
Subscribe
Login
Please login to comment
0 Discussion