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.
Python code
9 linesdef 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
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
- Use a temporary variable: `temp = lst[i]; lst[i] = lst[j]; lst[j] = temp` for clarity
- 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
More from Lists & loops
- Check if List is Sorted Ascending in Python easy
- Compare Two Lists in Python: Common, Only in First, Only in Second easy
- Convert a List of Integers to a Comma-Separated String in Python easy
- Enumerate a Python List with a Custom Start Index easy
- Extract Data by Type from a List in Python: Numbers and Strings easy
- Find All Occurrences of an Item in a Python List easy
Keep learning
Related tutorials and quizzes for this topic.