Thursday, December 26, 2024
Google search engine
HomeLanguagesPython Reverse List

Python Reverse List

Whenever you work with list dataType in Python. So many times you need to do some manipulation in the python list. In this post, you will learn how to reverse the python list.

In this python list reverse post, we will do some queries related to python list, such as how to reverse a list in python without using reverse function, how to reverse a list in python using for loop, reverse list python using slicing, reverse list python using the reverse(), etc.

If you want to learn how to reverse string in Python too, then you have this python reverse string.

Reverse list python

Now you will learn all the ways how to reverse the list in Python one by one:

1: Python reverse list using the reverse function

Python List reverse()

The python reverse() function is used to reverse the elements/items of a given python list.

The syntax of reverse() method is:

list.reverse()

Note:- The reverse() function doesn’t take any argument. And The reverse() function doesn’t return any value. It only reverses the elements and updates the list.

Python program to reverse a list using reverse() function is below:

# Laptop brand list
lp = ['Dell', 'HP', 'Acer']

print('Original List:', lp)

# List Reverse
lp.reverse()

# updated list
print('Updated List:', lp)

Output

Original List: ['Dell', 'HP', 'Acer']
Updated List: ['Acer', 'HP', 'Dell']

2: How to reverse a list in python using for loop

In the above example, you learned how to reverse the Python list by using the reverse () function.

Now we will learn how to reverse the list in Python using the for loop.

python program to reverse a list using for loop Or python program to reverse a list without using reverse function:

# Laptop brand list
lp = ['Dell', 'HP', 'Acer']

print('Original List:', lp)

# Print Python list element in reverse order using for loop
for l in reversed(lp):
    print(l)

Output

 Original List: ['Dell', 'HP', 'Acer']
 Acer
 HP
 Dell

3: How to reverse a list in python using slicing

In the above example, you learned how to reverse the Python list by using the for loop().

Now we will learn how to reverse the list in Python using slicing.

python program to reverse a list using slicing and wihout using any built-in python list function/method:

def Reverse(lst): 
    new_lst = lst[::-1] 
    return new_lst 

# Laptop brand list
lp = ['Dell', 'HP', 'Acer']

print('Original List:', lp)

# List Reverse
print('Updated List:', Reverse(lp))

Output

Original List: ['Dell', 'HP', 'Acer']
Updated List: ['Acer', 'HP', 'Dell']
Dominic Rubhabha-Wardslaus
Dominic Rubhabha-Wardslaushttp://wardslaus.com
infosec,malicious & dos attacks generator, boot rom exploit philanthropist , wild hacker , game developer,
RELATED ARTICLES

Most Popular

Recent Comments