Problem Formulation
Given a list of size n
and two indices i,j < n
.
Swap the element at index i
with the element at index j
, so that the element list[i]
is now at position j
and the original element list[j]
is now at position i
.
Examples:
- Swapping indices
0
and2
in list[1, 2, 3]
modifies the list to[3, 2, 1]
. - Swapping indices
1
and2
in list[1, 2, 3]
modifies the list to[1, 3, 2]
. - Swapping indices
1
and3
in list['alice', 'bob', 'carl', 'denis']
modifies the list to
.['alice', 'denis', 'carl', 'bob']
Method 1: Multiple Assignment
To swap two list elements by index i
and j
, use the multiple assignment expression lst[i], lst[j] = lst[j], lst[i]
that assigns the element at index i
to index j
and vice versa.
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
j
andi
by running the right-hand side of the assignment operation. - Second, it assigns the obtained elements in one go to the inverse indices
i
andj
(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 x
and y
by value, get the index of their first occurrences using the list.index(x)
and list.index(y)
methods and assign the result to variables i
and j
, respectively. Then apply the multiple assignment expression 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:
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 list.index()
method?
π‘ Background: The list.index(value)
method returns the index of the value
argument in the list
. You can use optional start
and 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 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.
Python One-Liners will 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.