Reverse an array in Python
This method has no return value, but does reverse sort the elements of the list.
The reversed function returns a reversed iterator. list is the sequence of transformations and can be tuple, string, list or range.
reversed(list)
You can reverse list or reverse array (see bottom).
Related course: Complete Python Programming Course & Exercises
reverse a list
The program below reverses a list and several other sequences:
#!/usr/bin/python
aList = [123, 'xyz', 'zara', 'abc', 'xyz']
aList.reverse()
print("List : ", aList)
# String
seqString = 'Python'
print(list(reversed(seqString)))
# tuple
seqTuple = ('P', 'y', 't', 'h', 'o', 'n')
print(list(reversed(seqTuple)))
# range
seqRange = range(5, 9)
print(list(reversed(seqRange)))
# List
seqList = [1, 2, 4, 3, 5]
print(list(reversed(seqList)))
Results
List : ['xyz', 'abc', 'zara', 'xyz', 123]
['n', 'o', 'h', 't', 'y', 'P']
['n', 'o', 'h', 't', 'y', 'P']
[8, 7, 6, 5]
[5, 3, 4, 2, 1]
reverse list example
Print the list backwards.
# Define an array of car brands
cars = ['bmw', 'audi', 'benz']
# Export raw data
print('Export raw data')
print(cars)
# Calling reverse() reverses the order
cars.reverse()
# Export data in reverse order
print('\n output flipped data')
print(cars)
Exporting raw data
['bmw', 'audi', 'benz']
Output of flipped data
['benz', 'audi', 'bmw']
python array reverse
There is a very simple way to reverse array (numpy) in python
import numpy as np
a = np.array([1,2,3,4,5,6])
b=a[::-1]
print(b)
Results:
[6, 5, 4, 3, 2, 1]
Alternatively, you can use the flipud function
import numpy as np
a = np.array([1,2,3,4,5,6])
b== np.flipud(ini_array)
print(b)
The results are also
[6, 5, 4, 3, 2, 1]