03-31-2022, 01:50 AM
How to Swap List Elements in Python?
Problem Formulation
Given a list of size and two indices .
Swap the element at index with the element at index , so that the element is now at position and the original element is now at position .
Examples:
Method 1: Multiple Assignment
To swap two list elements by index and , use the multiple assignment expression that assigns the element at index to index and vice versa.
The highlighted line works as follows:
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 and by value, get the index of their first occurrences using the and methods and assign the result to variables and , respectively. Then apply the multiple assignment expression 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:
Do you need a quick refresher on the method?
Background: The method returns the index of the argument in the . You can use optional and 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 .
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]](https://blog.finxter.com/wp-content/uploads/2020/06/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:
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!!
Problem Formulation
Given a list of size
Code:
nCode:
i,j < nSwap the element at index
Code:
iCode:
jCode:
list[i]Code:
jCode:
list[j]Code:
iExamples:
- Swapping indices and in listCode:
2modifies the list toCode:[1, 2, 3].Code:[3, 2, 1]
- Swapping indices andCode:
1in listCode:2modifies the list toCode:[1, 2, 3].Code:[1, 3, 2]
- Swapping indices andCode:
1in listCode:3modifies the list toCode:['alice', 'bob', 'carl', 'denis'].Code:['alice', 'denis', 'carl', 'bob']
Method 1: Multiple Assignment
To swap two list elements by index
Code:
iCode:
jCode:
lst[i], lst[j] = lst[j], lst[i]Code:
iCode:
jCode:
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 andCode:
jby running the right-hand side of the assignment operation.Code:i
- Second, it assigns the obtained elements in one go to the inverse indices andCode:
i(see left-hand side of the assignment operation).Code:j
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:
xCode:
yCode:
list.index(x)Code:
list.index(y)Code:
iCode:
jCode:
lst[i], lst[j] = lst[j], lst[i]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()
Background: The Code:
list.index(value)Code:
valueCode:
listCode:
startCode:
stopCode:
ValueErrorFeel 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]](https://blog.finxter.com/wp-content/uploads/2020/06/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!!

