How to Swap Two Indices in a Python List

Swap two elements at given indices in a Python list using simultaneous assignment, then return the modified list.

Easy Python 3.9+ Aug 9, 2026 Lists & loops 14 views 0 copies

Python code

9 lines
Python 3.9+
def swap_indices(lst, i, j):
    lst[i], lst[j] = lst[j], lst[i]
    return lst

if __name__ == "__main__":
    my_list = [10, 20, 30, 40, 50]
    print("Original list:", my_list)
    swapped = swap_indices(my_list, 1, 3)
    print("After swapping indices 1 and 3:", swapped)

Output

stdout
Original list: [10, 20, 30, 40, 50]
After swapping indices 1 and 3: [10, 40, 30, 20, 50]

How it works

The swap_indices function uses Python's simultaneous assignment (lst[i], lst[j] = lst[j], lst[i]), which evaluates both right-hand side values before assigning — so no temporary variable is needed. Swapping happens in place on the original list (lists are mutable and passed by reference), and the function returns that same list object for convenience. The if __name__ == "__main__" guard lets you run the example directly or import the function elsewhere without triggering output.

Common mistakes

  • Using `lst[i] = lst[j]` before `lst[j] = lst[i]` (loses data without a temp variable)
  • Swapping out-of-range indices without checking, causing IndexError
  • Expecting the function to return a new list instead of mutating the original

Variations

  1. Use a temporary variable: `temp = lst[i]; lst[i] = lst[j]; lst[j] = temp` for clarity
  2. Use slicing to create a new swapped list: `new_lst = lst.copy(); new_lst[i], new_lst[j] = lst[j], lst[i]`

Real-world use cases

  • Reordering playlist or queue items after user drag-and-drop actions.
  • Implementing in-place sorting helpers like swapping pivot elements during quicksort.
  • Swapping configuration values or labels between two positions in a settings array.

Sponsored

Run this sample

Open the browser IDE to tweak the example and see results without installing anything.

Open editor

More from Lists & loops

Related tutorials and quizzes for this topic.