There are several different approaches on how to reverse an array in Python.
They include:
- Reversing an array using list slicing.
- Reversing an array using Data Structures and Algorithms.
- Reversing an array using List methods and functions.
Reversing An Array In Python Using Data Structures & Algorithms
def reverse(nums):
#Pointing to the first element
start_index = 0
#Pointing to the last element
end_index = len(nums)-1
while end_index > start_index:
nums[start_index],nums[end_index] = nums[end_index],nums[start_index]
start_index = start_index + 1
end_index = end_index -1
if __name__ == '__main__':
n = [1,2,3,4,5]
reverse(n)
print(n)
Output:
[5,4,3,2,1]
Reversing A Python Array Using List Slicing
array = [1,2,3,4,5]
print(array[::-1])
Output:
[5,4,3,2,1]
Reverse An Array Using List Methods And Functions
array = [1,2,3,4,5]
array.reverse()
print(array)
Output:
[5,4,3,2,1]