SoFunction
Updated on 2025-04-13

4 ways to reverse python list

Lists are one of the basic and most commonly used data structures in Python. They are a mutable and ordered collection of objects that can also store duplicate values. In some applications, it may be necessary to arrange the list elements in reverse order, that is, all elements are inverted.

The following summarizes 4 common inversion methods for Python lists:

1. The reverse() method of list object

Syntax: List name.reverse()
This method does not return a value, and all elements in the list are in reverse order in place

# reverse() methoda = [1, 2, 3, 4, 5, 6, 7, 'abc', 'def']
()
print('List inversion result:', a)

List inversion result: [‘def’, ‘abc’, 7, 6, 5, 4, 3, 2, 1]

2. Built-in reversed() function

Syntax: reversed (list name)
Unlike the reverse() method, the built-in function reversed() does not make any modifications to the original list, but returns an iterative object arranged in reverse order.

# Built-in reversed() functiona = [1, 2, 3, 4, 5, 6, 7, 'abc', 'def']
a1 = reversed(a)
print('List inversion result (iteration object):', a1)
print('The result of the list inversion is converted to a list:', list(a1))

List inversion result (iteration object): <list_reverseiterator object at 0x00000243EF467A20>
The list inversion result is converted into a list: [‘def’, ‘abc’, 7, 6, 5, 4, 3, 2, 1]

3. Slice

Syntax: List name [x:y:z]
x: The slice start position, default is 0
y: The slice cutoff (but not included) position, default to the list length
z: The step size of the slice, default is 1; -1 means slice starting from the last element

# Slice inversiona = [1, 2, 3, 4, 5, 6, 7, 'abc', 'def']
print('List inversion result:', a[::-1])

List inversion result: [‘def’, ‘abc’, 7, 6, 5, 4, 3, 2, 1]

4. Use for loops

# Use a for loopa = [1, 2, 3, 4, 5, 6, 7, 'abc', 'def']
a1 = [a[len(a)-i-1] for i in range(len(a))]
print('List inversion result:', a1)

List inversion result: [‘def’, ‘abc’, 7, 6, 5, 4, 3, 2, 1]

This is the end of this article about 4 methods of python list inversion. For more related python list inversion content, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!