October DealsAmazon USOctober deal check: compare before you payAmazon US: current deals, useful picks and tech finds.Check DealsPC HealthRecommendedCrashes, freezes, slowdowns? Check your PC nowSpot repairable issues before they interrupt work.Check PCOctober DealsAmazon USDeal season is back - check today's better picksAmazon US: current deals, useful picks and tech finds.See Picks×
Skip to content
World desk2 min

Python Program to Swap Two Elements in a List

Swap two list positions in Python with one in-place multiple-assignment statement, and understand indexes, mutability, and common errors.

What’s actually slowing this PC down?

Pick the symptom - the matching free tool is one click away.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Use Python’s multiple-assignment syntax to swap two list elements in place: items[i], items[j] = items[j], items[i]. The indexes identify the positions to exchange, and Python lists count positions from zero.

Swap two list elements with one statement

Here is a complete example that exchanges the elements at indexes 1 and 3:

items = [10, 20, 30, 40]
i, j = 1, 3

items[i], items[j] = items[j], items[i]
print(items)  # [10, 40, 30, 20]

The right side supplies the two values in reversed order; the left side assigns them to the selected positions. Python describes this as multiple assignment combining tuple packing and sequence unpacking. Python’s data structures tutorial explains the assignment behavior, and the language reference documents subscriptions as assignment targets.

What the statement changes

This operation changes the existing list; it does not create a replacement list. Indexed assignment updates an element of the mutable list. Python’s informal introduction explains that assignment does not copy the underlying data.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

For example, if another variable refers to the same list, it will observe the swapped contents too:

items = ["red", "blue"]
alias = items

items[0], items[1] = items[1], items[0]
print(alias)  # ["blue", "red"]

Use a temporary variable for an explicit version

If separate steps make the exchange easier to follow, save one value before overwriting its position:

temp = items[i]
items[i] = items[j]
items[j] = temp

This also mutates the original list. The tuple-unpacking form is more concise; choose based on which is clearer for the reader or codebase.

Indexes and common edge cases

  • Indexes start at zero. In a four-element list, valid positive indexes are 0, 1, 2, and 3.
  • Negative indexes count from the end. For example, items[-1] selects the final element.
  • Invalid indexes raise IndexError. An assignment to an out-of-range list position fails; it does not append a new element.
  • The same index can be used twice. If i == j, the element is assigned back to its own position, so the list’s contents do not change.

These index and assignment rules are covered in the Python language reference.

Free tools Windows power users keep installed

One-click scans. No signup required.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Lists are mutable; tuples are not

The indexed swap works because lists allow item assignment. A tuple is immutable, so assigning to tuple positions this way raises TypeError. If you need to change values, convert the tuple to a list first; if you need a new tuple, construct one with the desired order instead. See the Python data structures tutorial for the distinction.

Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Support on Ko-Fi

Validate indexes when they come from input

If indexes come from a user or another untrusted source, decide whether your program accepts negative indexes. To allow only positions from zero through the final list index, check them before swapping:

if not (0 <= i < len(items) and 0 <= j < len(items)):
    raise IndexError("list index out of range")

items[i], items[j] = items[j], items[i]

For an empty list, no index passes this check. If negative indexes are intended, omit the nonnegative restriction and handle values below -len(items) or at least len(items) as invalid.

Product prices and availability are accurate as of the date/time indicated and are subject to change. Any price and availability information displayed on Amazon at the time of purchase will apply.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Leave a Reply

Your email address will not be published. Required fields are marked *

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

More from the Wire

  1. World desk4 min
    How to Spot an AI Voice Scam Before Sending MoneyDon’t rely on how a caller sounds. Pause, call back through a known number, and verify the emergency with another trusted person before sending money.
  2. Mountain View desk4 min
    Google’s SynthID Detector: How to Check AI-Generated Images, Video and AudioGoogle’s SynthID Detector looks for an embedded watermark in supported images, video and audio. Here is what its results do—and do not—show.
  3. Redmond desk20 min
    How to create a link to File or Folder in Windows 11Windows 11 gives you several ways to point to a file or folder without moving or duplicating it. You can create a desktop shortcut,…
Recommended PC Tool
Recommended PC Tool
Crashes, No Sound, or Screen Glitches?Free driver scan
PC Slower Than It Used to Be?Free scan - under a minute

Two free Windows tools

One Free Minute Could Fix That PC

Before you go - each of these free tools takes about a minute and tackles what quietly slows a Windows PC down.

Special offer. View Outbyte info, uninstall instructions, EULA, and Privacy Policy.