Python reverse list | with reverse() function & Other ways

You can reverse Python List using an inbuilt reverse() function and other ways. The python reverse() function is mainly used to reverses the elements of a given list(Array).

In this tutorial, our main top will be the reverse() function.

Syntax

doesn’t take any argument.

list.reverse()

Return Value

It Doesn’t return any value. List elements will be updated in reversed order.

Way to reverse a list in Python

  • Python reverse() function
  • Using the reversed() function
  • Using the slicing technique.
  • Loops: for-loop and while loop

Python reverse list Examples

1. reverse() function

It will modify the original list.

list1 = [1, 4, 3, 6, 7]

# Reversing List
list1.reverse()

print(list1)

Output: [7, 6, 3, 4, 1]

2. reversed() function

we get a reverse iterator which we use to cycle through the list.

# Reversing a list using reversed()
def revList(list):
    return [ele for ele in reversed(list)]


list1 = [0, 1, 2, 3, 4, 5]
print(revList(list1))

Output: [5, 4, 3, 2, 1, 0]

3. Reverse a List Using Slicing Operator

# Reversing a list using slicing technique
def revList(lst):
    new_lst = lst[::-1]
    return new_lst


list1 = [0, 1, 2, 3, 4, 5]
print(revList(list1))

4. Using for loop & reversed() function

# Operating System List
os = ['Windows', 'macOS', 'Linux']

# Printing Elements in Reversed Order
for o in reversed(os):
    print(o)

Output: Linux
macOS
Windows

Q: How to reverse an array in Python?

Answer: You can use the reverse() function to reverse an Array element in python. Array and list are the same things as python programming.

list.reverse()

Q: How to reverse a list in python using for loop?

Answer: You can use for-loop which reverses a list in python without reverse function. See the below example program.

my_list = [1, 2, 3, 4, 5]  # list
new_list = []      # empty list
for item in my_list:
    new_list.insert(0, item)  # insert items to new_list at index-position [0]
print(new_list)

Output: [5, 4, 3, 2, 1]

Reverse empty list

No error occurs and the list will be the same because of no elements in the list.

list1 = []

# Reversing List
list1.reverse()

print(list1)

Output: []

Do comment if you knew any other method, doubts, or suggestions in the comment section on this tutorial.

Note:
IDE: PyCharm 2020.1.1 (Community Edition)
macOS 10.15.4
Python 3.7
All Python Examples are in Python 3, so Maybe its different from python 2 or upgraded versions.


Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.