Founding Batch Offer ยท HLD ยท LLD ยท System Design at โ‚น799 until 30 Nov

Reverse Array

Reverse a Python list by swapping symmetric positions. Students trace a half-length loop and calculate the partner index without swapping every pair twice.

IntermediatePhase 4 - Level 3: TransformationExample 6 of 10
reverse-array.py
1# Take array
2n = int(input("Enter array size: "))
3arr = []
4for i in range(n):
5 arr.append(int(input(f"Element {i+1}: ")))
6
7# Reverse array
8print(f"Original: {arr}")
9for i in range(len(arr) // 2):
10 arr[i], arr[len(arr) - 1 - i] = arr[len(arr) - 1 - i], arr[i]
11
12print(f"Reversed: {arr}")

Output

Enter array size: 5
Element 1: 1
Element 2: 2
Element 3: 3
Element 4: 4
Element 5: 5
Original: [1, 2, 3, 4, 5]
Reversed: [5, 4, 3, 2, 1]

In this one

  • Pair symmetric indexes
  • Limit swaps to half
  • Leave an odd center

How it works

  1. 1

    Visit the first half of arr's indexes.

  2. 2

    Pair i with len(arr) - 1 - i.

  3. 3

    Swap each pair once and print the reversed list.

Edge cases

What happens to an odd middle element?

What happens to an odd middle element?

It remains in place.

Why stop at half the length?

Why stop at half the length?

Every swap handles two symmetric positions.

What's going on

Index i is paired with len(arr) - 1 - i. The loop stops after half the length using integer floor division.

Each pair swaps in place. An odd-length list has a center element that stays where it is. Visiting the whole list would swap pairs back again, undoing the reversal. Empty and one-element lists naturally require no swaps.

What happens to an odd middle element? It remains in place.

Why stop at half the length? Every swap handles two symmetric positions.

Quiz

Tap an option. The answer stays hidden until you pick.

Question 1

Does this allocate a reversed list?

Pick an answer to check it.

Question 2

What happens to an odd middle element?

Pick an answer to check it.

Questions people ask

What happens to an odd middle element?

It remains in place.

Why stop at half the length?

Every swap handles two symmetric positions.

Does this allocate a reversed list?

No, it swaps in place.