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

5/5 - (1 vote)

Problem Formulation: Replacing One Element


  • 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


  • 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]

# ['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

# ['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
# ['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))]
# ['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: Master the Single Line First!

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 (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!!