How to Reverse a List in Python


Here this example will teach us how to quickly reverse an existing list without using any built-in Python function.

Source Code

#! /usr/bin/env python3
# -*- coding: utf-8 -*-

a = [1,2,3,4,5,6]
N = len(a)
print('Original Array:')
print(a)

for i in range(len(a)//2):
    a[i],a[N - i - 1] = a[N - i - 1],a[i]
print('Reversed Array:')
print(a)

Output:

Original Array:
[1, 2, 3, 4, 5, 6]
Reversed Array:
[6, 5, 4, 3, 2, 1]
Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments
Advertisement