Replace element in 2d list python

  • Problem Formulation: Replacing One Element
  • Solution Indexing
  • Problem Formulation: Replacing Multiple Elements
  • Method 1: For Loop
  • Method 2: zip() and For Loop
  • Method 3: NumPy + Slice Assignment
  • Method 4: Python One-Liner Solution
  • Python One-Liners Book: Master the Single Line First!

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: Master the Single Line First!

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

Replace element in 2d list python

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

Replace element in 2d list python

While working as a researcher in distributed systems, Dr. Christian Mayer found his love for teaching computer science students.

To help students reach higher levels of Python success, he founded the programming education website Finxter.com. He’s author of the popular programming book Python One-Liners (NoStarch 2020), coauthor of the Coffee Break Python series of self-published books, computer science enthusiast, freelancer, and owner of one of the top 10 largest Python blogs worldwide.

His passions are writing, reading, and coding. But his greatest passion is to serve aspiring coders through Finxter and help them to boost their skills. You can join his free email academy here.

How do I change the elements in a 2d list?

“change 1 element in 2d list python” Code Answer.
multi_dimension = [[1, 2, 3], [4, 5, 6]].
multi_dimension[1][1] = 7 # Value 5 (element 2) in list 2 is converted to 7..
other_example[[[0, 1], [2, 3]], [[4, 5], [6, 7]]].
other_example[0][1][0] = 8 # Value 2 (Element 2) in list2 of list1 in other_.
# example is changed to 8..

Can you replace an element in a list Python?

We can replace values inside the list using slicing. First, we find the index of variable that we want to replace and store it in variable 'i'. Then, we replace that item with a new value using list slicing.

How do you replace words in a list Python?

Replace a specific string in a list. If you want to replace the string of elements of a list, use the string method replace() for each element with the list comprehension. If there is no string to be replaced, applying replace() will not change it, so you don't need to select an element with if condition .

How do you replace a number with another number in Python?

replace() Parameters The replace() method can take maximum of 3 parameters: old - old substring you want to replace. new - new substring which will replace the old substring. count (optional) - the number of times you want to replace the old substring with the new substring.