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]
The Ultimate Python Ethical Hacking Course
=> Join the Waitlist for Early Access.
By subscribing, you agree to get emails from me, Tanner Abraham. I'll respect your privacy and you can unsubscribe any time.
Reverse An Array Using List Methods And Functions
array = [1,2,3,4,5]
array.reverse()
print(array)
Output:
[5,4,3,2,1]
Tanner Abraham
Data Scientist and Software Engineer with a focus on experimental projects in new budding technologies that incorporate machine learning and quantum computing into web applications.The Ultimate Python Ethical Hacking Course
=> Join the Waitlist for Early Access.
By subscribing, you agree to get emails from me, Tanner Abraham. I'll respect your privacy and you can unsubscribe any time.