
Reverse a Python list by negative step slicing
A Python list can be reverses by reverse()
.
a = ['Book', 'Note', 'Pen']
a.reverse()
print(a) # ['Pen', 'Note', 'Book']
Slicing syntax
The Python slicing syntax (with a negative step) can be used to reverse a list.
a = [1, 2, 3, 4, 5]
b = a[::-1]
print(a) # [1, 2, 3, 4, 5]
print(b) # [5, 4, 3, 2, 1]
Format
a[start:stop:step]
The start
, stop
, step
options can be omitted. In the example, the start and stop are omitted and the step is -1. The a
doesn't change and slicing returns a new reversed list.
Note that a tuple and range can be reversed in the same way.
t1 = (1, 2, 3)
t2 = t1[::-1]
print(t2) # (3, 2, 1)
r1 = range(6)
r2 = r1[::-1]
for i in r2:
print(i)
# 5
# 4
# 3
# 2
# 1
# 0
A NumPy array can be also reversed by slicing.
import numpy
a = numpy.array([1, 2, 3, 4])
b = a[::-1]
print(a) # [1 2 3 4]
print(b) # [4 3 2 1]
The reverse() returns None
a = [1, 2, 3]
b = a.reverse()
print(b) # None
In case of an empty list
An empty list is reversed to itself.
a = []
a.reverse()
print(a) # []
Note: The id doesn't change by reversing
The object id doesn't change after being reversed.
a = [1, 2, 3, 4, 5]
print(id(a)) # 4490770176
a.reverse()
print(id(a)) # 4490770176
Comments
Powered by Markdown