Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
[Tut] How to Swap List Elements in Python?
1
How to Swap List Elements in Python?

Problem Formulation

Given a list of size
Code:
n
and two indices
Code:
i,j < n
.

Swap the element at index
Code:
i
with the element at index
Code:
j
, so that the element
Code:
list[i]
is now at position
Code:
j
and the original element
Code:
list[j]
is now at position
Code:
i
.

Examples:
  • Swapping indices and
    Code:
    2
    in list
    Code:
    [1, 2, 3]
    modifies the list to
    Code:
    [3, 2, 1]
    .

  • Swapping indices
    Code:
    1
    and
    Code:
    2
    in list
    Code:
    [1, 2, 3]
    modifies the list to
    Code:
    [1, 3, 2]
    .

  • Swapping indices
    Code:
    1
    and
    Code:
    3
    in list
    Code:
    ['alice', 'bob', 'carl', 'denis']
    modifies the list to
    Code:
    ['alice', 'denis', 'carl', 'bob']
    .

Method 1: Multiple Assignment

To swap two list elements by index
Code:
i
and
Code:
j
, use the multiple assignment expression
Code:
lst[i], lst[j] = lst[j], lst[i]
that assigns the element at index
Code:
i
to index
Code:
j
and vice versa.

Code:
lst = ['alice', 'bob', 'carl'] i, j = 0, 2 # Swap index i=0 with index j=2 lst[i], lst[j] = lst[j], lst[i] print(lst) # ['carl', 'bob', 'alice']

The highlighted line works as follows:
  • First, it obtains the elements at positions
    Code:
    j
    and
    Code:
    i
    by running the right-hand side of the assignment operation.

  • Second, it assigns the obtained elements in one go to the inverse indices
    Code:
    i
    and
    Code:
    j
    (see left-hand side of the assignment operation).

To help you better understand this code snippet, I’ve recorded a quick video that shows you how the generalization of multiple assignment, i.e., slice assignment, works as a Python One-Liner:



Method 2: Swap Two Elements by Value Using indexof()

Let’s quickly discuss a variant of this problem whereby you want to swap two elements but you don’t know their indices yet.

To swap two list elements
Code:
x
and
Code:
y
by value, get the index of their first occurrences using the
Code:
list.index(x)
and
Code:
list.index(y)
methods and assign the result to variables
Code:
i
and
Code:
j
, respectively. Then apply the multiple assignment expression
Code:
lst[i], lst[j] = lst[j], lst[i]
to swap the elements.

The latter part, i.e., swapping the list elements, remains the same. The main difference is highlighted in the following code snippet:

Code:
lst = ['alice', 'bob', 'carl'] x, y = 'alice', 'carl' # Get indices i and j associated with elements x and y i, j = lst.index(x), lst.index(y) # Swap element at index i with element at index j lst[i], lst[j] = lst[j], lst[i] print(lst) # ['carl', 'bob', 'alice']

Do you need a quick refresher on the
Code:
list.index()
method?

[Image: 1f4a1.png] Background: The
Code:
list.index(value)
method returns the index of the
Code:
value
argument in the
Code:
list
. You can use optional
Code:
start
and
Code:
stop
arguments to limit the index range where to search for the value in the list. If the value is not in the list, the method throws a
Code:
ValueError
.

Feel free to also watch the following quick explainer video:



Python One-Liners Book: Master the Single Line First!

Python programmers will improve their computer science skills with these useful one-liners.

[Image: 3D_cover-1024x944.jpg]

Python One-Linerswill teach you how to read and write “one-liners”: concise statements of useful functionality packed into a single line of code. You’ll learn how to systematically unpack and understand any line of Python code, and write eloquent, powerfully compressed Python like an expert.

The book’s five chapters cover (1) tips and tricks, (2) regular expressions, (3) machine learning, (4) core data science topics, and (5) useful algorithms.

Detailed explanations of one-liners introduce key computer science concepts and boost your coding and analytical skills. You’ll learn about advanced Python features such as list comprehension, slicing, lambda functions, regular expressions, map and reduce functions, and slice assignments.

You’ll also learn how to:
  • Leverage data structures to solve real-world problems, like using Boolean indexing to find cities with above-average pollution

  • Use NumPy basics such as array, shape, axis, type, broadcasting, advanced indexing, slicing, sorting, searching, aggregating, and statistics

  • Calculate basic statistics of multidimensional data arrays and the K-Means algorithms for unsupervised learning

  • Create more advanced regular expressions using grouping and named groups, negative lookaheads, escaped characters, whitespaces, character sets (and negative characters sets), and greedy/nongreedy operators

  • Understand a wide range of computer science topics, including anagrams, palindromes, supersets, permutations, factorials, prime numbers, Fibonacci numbers, obfuscation, searching, and algorithmic sorting

By the end of the book, you’ll know how to write Python at its most refined, and create concise, beautiful pieces of “Python art” in merely a single line.

Get your Python One-Liners on Amazon!!
Reply

Users browsing this thread:
1 Guest(s)


Forum Jump: