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

Swap First & Last Elements

Swap a list's first and last elements safely. Students use a nonempty guard, negative indexing, and simultaneous assignment without overwriting either endpoint.

IntermediatePhase 4 - Level 3: TransformationExample 5 of 10
swap-first-last-elements.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# Swap first and last
8if len(arr) > 0:
9 arr[0], arr[-1] = arr[-1], arr[0]
10
11print(f"After swap: {arr}")

Output

Enter array size: 5
Element 1: 1
Element 2: 2
Element 3: 3
Element 4: 4
Element 5: 5
After swap: [5, 2, 3, 4, 1]

In this one

  • Guard endpoint access
  • Use negative indexing
  • Swap simultaneously

How it works

  1. 1

    Check that arr is nonempty.

  2. 2

    Read both old endpoints on the assignment's right side.

  3. 3

    Write them into exchanged positions.

Edge cases

What if the list is empty?

What if the list is empty?

The guard skips the swap.

What if it has one value?

What if it has one value?

That value swaps with itself and stays unchanged.

What's going on

The guard checks that an endpoint exists before indexing. arr[0] is the first element and arr[-1] the last.

The right-hand pair is evaluated before either assignment, preserving both original values. Only endpoints move; middle entries keep their positions. For a one-element list, both references name the same slot, so the swap leaves it unchanged.

What if the list is empty? The guard skips the swap.

What if it has one value? That value swaps with itself and stays unchanged.

Quiz

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

Question 1

Why use paired assignment?

Pick an answer to check it.

Question 2

What if the list is empty?

Pick an answer to check it.

Questions people ask

What if the list is empty?

The guard skips the swap.

What if it has one value?

That value swaps with itself and stays unchanged.

Why use paired assignment?

Both old endpoint values are captured before writing.