How to swap list elements in Python

Learn how to swap list elements in Python. Discover multiple methods, tips, real-world uses, and how to debug common errors.

How to swap list elements in Python
Published on: 
Mon
Apr 6, 2026
Updated on: 
Fri
Apr 10, 2026
The Replit Team

To swap elements in a Python list is a frequent task for data manipulation and algorithm design. Python provides several efficient methods to accomplish this common operation with clean, readable code.

In this article, you'll explore various techniques to swap list items, complete with real-world applications and performance tips. You will also find practical debugging advice to help you master this essential skill.

Using a temporary variable

my_list = [1, 2, 3, 4, 5]
temp = my_list[1]
my_list[1] = my_list[3]
my_list[3] = temp
print(my_list)--OUTPUT--[1, 4, 3, 2, 5]

This classic approach uses a temporary variable, temp, to act as a placeholder during the swap. It's a fundamental technique that prevents data loss, ensuring the original value isn't overwritten before the exchange is complete.

  • First, the value of my_list[1] is copied to temp.
  • Next, my_list[1] is updated with the value from my_list[3].
  • Finally, my_list[3] receives the value originally stored in temp.

This method's explicitness makes it highly readable and a reliable choice in any situation.

Common swapping techniques

Beyond the classic temporary variable, Python offers several more idiomatic techniques for swapping elements with greater flexibility and conciseness.

Using tuple unpacking with variable, variable syntax

my_list = [1, 2, 3, 4, 5]
my_list[0], my_list[2] = my_list[2], my_list[0]
print(my_list)--OUTPUT--[3, 2, 1, 4, 5]

This approach, known as tuple unpacking, is a more concise and idiomatic way to swap elements in Python. It's often preferred for its readability and elegance, accomplishing the swap in a single, expressive line.

  • Python first evaluates the expression on the right side, (my_list[2], my_list[0]), creating a temporary tuple in memory.
  • It then unpacks the values from this new tuple and assigns them to the list indices on the left side, completing the exchange without needing an explicit temporary variable.

Using index variables for dynamic swapping

my_list = ['a', 'b', 'c', 'd', 'e']
i, j = 1, 3
my_list[i], my_list[j] = my_list[j], my_list[i]
print(my_list)--OUTPUT--['a', 'd', 'c', 'b', 'e']

This approach adds a layer of flexibility by using variables like i and j to hold the index positions. It makes your code more dynamic because the indices can be calculated or changed during program execution, rather than being hardcoded.

  • The variables i and j are assigned the integer indices 1 and 3.
  • The expression my_list[i], my_list[j] = my_list[j], my_list[i] then swaps the elements at those positions.

This method is especially useful in algorithms where the elements to be swapped are determined by logic within a loop or function.

Using the pop() and insert() methods

my_list = [10, 20, 30, 40, 50]
i, j = 0, 4
val_i = my_list.pop(i)
val_j = my_list.pop(j-1) # Adjust index after first pop
my_list.insert(i, val_j)
my_list.insert(j, val_i)
print(my_list)--OUTPUT--[50, 20, 30, 40, 10]

This technique combines the pop() and insert() methods to swap elements. While more verbose, it's a good exercise in list manipulation. However, it's generally less performant than tuple unpacking due to the overhead of resizing the list multiple times.

  • The pop() method first removes each element from its original position.
  • Because the list shrinks after the first removal, you must adjust the index for the second operation—this is why the code uses j-1.
  • Finally, insert() places the stored values into their new positions, completing the swap.

Advanced swapping patterns

Beyond simple two-element swaps, Python’s slicing and list comprehensions unlock more advanced patterns for manipulating multiple items at once.

Using slice operations with [::-1] for adjacent elements

my_list = ['apple', 'banana', 'cherry', 'date']
i = 1
my_list[i:i+2] = my_list[i:i+2][::-1]
print(my_list)--OUTPUT--['apple', 'cherry', 'banana', 'date']

This technique is perfect for swapping adjacent elements. The slice my_list[i:i+2] first selects a sublist containing 'banana' and 'cherry'. Then, the extended slice operator [::-1] creates a reversed copy of that sublist in memory.

  • Finally, a slice assignment operation replaces the original segment with the newly reversed one.
  • This powerful method isn't limited to two items—you can use it to reverse any contiguous block of elements within a list.

Creating a new list with swapped elements using comprehension

original = [5, 10, 15, 20, 25]
i, j = 1, 3
swapped = [original[j] if idx==i else original[i] if idx==j else original[idx] for idx in range(len(original))]
print(swapped)--OUTPUT--[5, 20, 15, 10, 25]

This list comprehension builds a new list, swapped, without altering the original list. It iterates through each index of the original list, deciding which value to place in the new one based on a series of conditional checks.

  • When the current index matches i, it appends the value from original[j].
  • When the index matches j, it appends the value from original[i].
  • For all other indices, it simply copies the element from the original list.

This approach is ideal when you need to preserve the original list for other operations.

Swapping multiple elements with slice assignment

my_list = [1, 2, 3, 4, 5, 6, 7, 8]
my_list[1:4], my_list[5:8] = my_list[5:8], my_list[1:4]
print(my_list)--OUTPUT--[1, 6, 7, 8, 5, 2, 3, 4]

This powerful pattern extends tuple unpacking to entire list slices, letting you swap non-adjacent sections of a list in a single, readable line. It's a highly efficient way to reorder multiple elements at once without manual iteration.

  • Python first evaluates the right side, creating a temporary tuple containing two sublists: [6, 7, 8] and [2, 3, 4].
  • It then uses slice assignment to unpack this tuple, replacing the original slice my_list[1:4] with the first sublist and my_list[5:8] with the second.

Move faster with Replit

Replit is an AI-powered development platform that comes with all Python dependencies pre-installed, so you can skip setup and start coding instantly. Instead of piecing together individual techniques, you can use Agent 4 to build a complete, working product directly from a description.

The Agent can take your idea and build a functional application. For example, you could describe tools like:

  • A task scheduler that swaps items in a priority list based on urgency.
  • A data formatting utility that reverses the order of first and last names in a user list before export.
  • A workflow customizer that reorders processing steps by swapping adjacent functions in a sequence.

Simply describe your app, and Replit will write the code, test it, and fix issues automatically, all within your browser.

Common errors and challenges

While swapping elements is usually straightforward, a few common pitfalls can lead to unexpected errors if you're not careful. Keep an eye out for these issues:

  • Attempting to swap elements between two different collections using tuple-unpacking syntax.
  • Receiving an IndexError when an index like my_list[j] falls outside the list's boundaries.
  • Unintentionally mutating shared object references when swapping an element like list[i], causing unexpected changes in other parts of your data.

Swapping across different collections with list[0] syntax

It's tempting to use tuple unpacking to swap entire collections, but this syntax is designed for elements. Applying it like list1[0], list2[0] = list2[0], list1[0] only swaps the specified items, not the lists themselves. See what happens below.

list1 = [1, 2, 3]
list2 = [4, 5, 6]
list1[0], list2[0] = list2[0], list1[0] # This works but is not what we want for whole collections
print(list1, list2) # [4, 2, 3] [1, 5, 6]

This assignment targets the elements at index [0], not the list variables themselves. As a result, only the first items are exchanged. The correct way to swap entire collections requires a different syntax, as shown below.

list1 = [1, 2, 3]
list2 = [4, 5, 6]
# To swap entire collections
list1, list2 = list2, list1
print(list1, list2) # [4, 5, 6] [1, 2, 3]

To swap entire collections, you reassign the variable names directly using list1, list2 = list2, list1. This simple tuple assignment makes the name list1 point to the object that list2 originally referenced, and vice versa. It’s a clean, Pythonic way to exchange the contents of two lists without modifying their internal elements one by one. This is the correct approach when you need to completely switch the data two variables are holding.

Out-of-range index errors when using my_list[j]

Out-of-range index errors when using my_list[j]

An IndexError is one of the most common issues you'll face. It happens when you try to access a list position that doesn't exist. Since Python lists are zero-indexed, the last valid index is always one less than the list's length.

For example, using an index equal to the list's length, such as len(my_list), will always cause an error. See what happens in the code below when you make this mistake.

my_list = [1, 2, 3, 4, 5]
i = 2
j = len(my_list) # This is out of range
my_list[i], my_list[j] = my_list[j], my_list[i] # IndexError: list index out of range
print(my_list)

The variable j is assigned len(my_list), which evaluates to 5. Because the list's last valid index is 4, the expression my_list[j] fails. Check the code below to see how to correctly manage index boundaries.

my_list = [1, 2, 3, 4, 5]
i = 2
j = len(my_list) - 1 # Correct index
my_list[i], my_list[j] = my_list[j], my_list[i]
print(my_list) # [1, 2, 5, 4, 3]

It's a simple fix: always remember that a list's last index is len(my_list) - 1. By setting j to the correct final index, the swap works as intended. Keep these points in mind:

  • The last valid index is always one less than the list's length.
  • Double-check index calculations, especially when they're determined dynamically inside loops or functions, to prevent common off-by-one errors.

Mutating shared references after using list[i] swapping

When your list contains other mutable objects, like lists, swapping with list[i] syntax can create unexpected side effects. You're not swapping copies but shared references, so modifying the new list can unintentionally alter the original. See what happens below.

list_a = [1, 2, 3]
list_b = [4, 5, 6]
original = [list_a, list_b]
swapped = [original[1], original[0]] # Creates new list with swapped references
swapped[0][0] = 99 # Modifies list_b, which affects both original and swapped
print(original, swapped) # [[1, 2, 3], [99, 5, 6]] [[99, 5, 6], [1, 2, 3]]

Because swapped contains references to the original inner lists, not copies, modifying an element like swapped[0][0] alters list_b everywhere. To avoid this entanglement, you need a different approach. The code below shows how.

list_a = [1, 2, 3]
list_b = [4, 5, 6]
original = [list_a, list_b]
swapped = [original[1][:], original[0][:]] # Create copies with slicing
swapped[0][0] = 99 # Modifies only the copy in swapped
print(original, swapped) # [[1, 2, 3], [4, 5, 6]] [[99, 5, 6], [1, 2, 3]]

To prevent unintended mutations, create shallow copies of the nested lists using slice notation like original[1][:]. This technique generates a new list containing the same elements, ensuring that swapped and original hold independent objects.

Now, any changes made to the lists inside swapped won't affect the original list. This is crucial for maintaining data integrity whenever your lists contain other mutable objects, such as lists or dictionaries.

Real-world applications

With a solid grasp of swapping techniques and their common errors, you can now apply them to build classic algorithms for sorting and shuffling.

Implementing bubble sort with swap operations

Bubble sort is a fundamental sorting algorithm that repeatedly steps through a list, compares adjacent elements, and swaps them if they are in the wrong order.

def bubble_sort(arr):
n = len(arr)
for i in range(n):
for j in range(0, n-i-1):
if arr[j] > arr[j+1]:
arr[j], arr[j+1] = arr[j+1], arr[j]
return arr

data = [64, 34, 25, 12, 22, 11, 90]
print(bubble_sort(data))

The bubble_sort function sorts the list in place using two nested loops. The outer loop ensures each element is visited, while the inner loop handles the comparisons. With each pass, the largest unsorted value moves to its final position at the end of the list.

  • The condition if arr[j] > arr[j+1] checks if an element is greater than its neighbor.
  • If it is, the line arr[j], arr[j+1] = arr[j+1], arr[j] swaps them using tuple unpacking.
  • The inner loop's range shrinks on each pass to avoid re-checking already sorted elements.

Implementing Fisher-Yates shuffle with random swap operations

The Fisher-Yates shuffle is a classic algorithm that randomizes a list by iterating through its elements and swapping each one with another at a random position.

import random

def shuffle_deck(deck):
for i in range(len(deck)-1, 0, -1):
j = random.randint(0, i)
deck[i], deck[j] = deck[j], deck[i]
return deck

cards = ['A♠', 'K♠', 'Q♠', 'J♠', '10♠']
print(shuffle_deck(cards))

The shuffle_deck function implements this algorithm by iterating backward through the list. This reverse loop is key—it ensures that once an element is placed toward the end of the list, it stays there, effectively shrinking the pool of items left to shuffle.

  • For each position i, the code generates a random index j from the remaining, unshuffled portion of the list using random.randint(0, i).
  • It then swaps the current element at deck[i] with the randomly selected element at deck[j].

This method guarantees that every possible permutation of the list is equally likely, resulting in an unbiased shuffle.

Get started with Replit

Now, turn these swapping techniques into a real tool with Replit Agent. Describe what you want, like "build a task manager that reorders items" or "create a card game shuffler that randomizes a deck."

The Agent writes the code, tests for errors, and deploys your application. Start building with Replit.

Get started free

Create and deploy websites, automations, internal tools, data pipelines and more in any programming language without setup, downloads or extra tools. All in a single cloud workspace with AI built in.

Get started free

Create and deploy websites, automations, internal tools, data pipelines and more in any programming language without setup, downloads or extra tools. All in a single cloud workspace with AI built in.