How to Replace One or More List Elements at Specific Indices in Python?

Problem Formulation: Replacing One Element

Given

  • List lst
  • Element x
  • Index i

How to replace the element at index i in the list lst with the new element x?

Solution Indexing

You use simple indexing using the square bracket notation lst[i] = x to replace the element at index i in list lst with the new element x.

>>> lst = ['Alice', 'Bob', 'Carl', 'Dave']
>>> x = 'Chris'
>>> i = 2
>>> lst[i] = x
>>> lst
['Alice', 'Bob', 'Chris', 'Dave']

But what if you want to replace multiple elements at multiple indices?

Problem Formulation: Replacing Multiple Elements

Given

  • List lst
  • Elements [x_0, x_1, ..., x_n]
  • Indices [i_0, i_1, ..., i_n]

How to replace the elements at indices i_0, i_1, ..., i_n in the list lst with the new elements x_0, x_1, ..., x_n in that order?

Method 1: For Loop

You can use the range() function to get the pair of the i-th index and the i-th replacement value in a for loop. Then, you replace all elements one-by-one.

lst = ['Alice', 'Bob', 'Carl', 'Dave', 'Elena', 'Frank', 'George']
repl = ['None', 'Foo', 'Bar']
indices = [0, 2, 5]


# Method 1: For Loop
for i in range(len(indices)):
    lst[indices[i]] = repl[i]

print(lst)
# ['None', 'Bob', 'Foo', 'Dave', 'Elena', 'Bar', 'George']

Method 2: zip() and For Loop

A more Pythonic approach is to zip together the indices and replacement values and then simply iterating over them in pairs using multiple assignments.

lst = ['Alice', 'Bob', 'Carl', 'Dave', 'Elena', 'Frank', 'George']
repl = ['None', 'Foo', 'Bar']
indices = [0, 2, 5]


# Method 2: zip() and for loop
for index, replacement in zip(indices, repl):
    lst[index] = replacement

print(lst)
# ['None' 'Bob' 'Foo' 'Dave' 'Elena' 'Bar' 'George']

Method 3: NumPy + Slice Assignment

Stand on the shoulders of giants! You can use NumPy’s powerful advanced indexing functionality to pass the list of indices to be replaced in the indexing scheme—and replacing those with all elements on the right of an assignment operation.

lst = ['Alice', 'Bob', 'Carl', 'Dave', 'Elena', 'Frank', 'George']
repl = ['None', 'Foo', 'Bar']
indices = [0, 2, 5]


# Method 3: NumPy + Slice Assignment
import numpy as np
lst = np.array(lst)
lst[indices] = repl
print(lst)
# ['None' 'Bob' 'Foo' 'Dave' 'Elena' 'Bar' 'George']

Method 4: Python One-Liner Solution

I love Python one-liners (that’s why I’ve written a book about them). Can we solve the multiple replacement problem in a single line? Yeah, sure!

lst = ['Alice', 'Bob', 'Carl', 'Dave', 'Elena', 'Frank', 'George']
repl = ['None', 'Foo', 'Bar']
indices = [0, 2, 5]

# Method 4: Python One-Liner
lst = [repl[indices.index(i)] if i in indices else lst[i] for i in range(len(lst))]
print(lst)
# ['None' 'Bob' 'Foo' 'Dave' 'Elena' 'Bar' 'George']
  • We use list comprehension [... for i in ...] to iterate over all indices from 0 to the length of the list.
  • We use the ternary operator ... if ... else ... to check whether this index is one that must be replaced.
  • If the index doesn’t have to be replaced, return the original element, otherwise return the replacement element.
  • We use the list.index() method to figure out the index of the element to replace the original list element.

Not very pretty, isn’t it? If you still want to learn how one-liners work, check out my book:

Python One-Liners Book

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

Python 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 tips and tricks, regular expressions, machine learning, core data science topics, and 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 Now!!