We could replace elements in a Python list in several ways. We can use Python list elements indexing, for loop, map function, and list comprehension methods. Show
This article will discuss the above methods to find and replace the Python list elements. Find and Replace the Python List Elements With the List Indexing MethodLet’s take the below list as an example. my_list=[5,10,7,5,6,8,5,15]We will change the element at the index 0 from 5 to 20. The example code is as follows. my_list=[5,10,7,5,6,8,5,15] my_list[0]=20 print(my_list)Output: [20, 10, 7, 5, 6, 8, 5, 15]Find and Replace the Python List Elements With the for Loop MethodWe use the enumerate() function in this method. It returns a enumerate object that also contains the counter together with the elements. When we combine the enumerate() function with the for loop, it iterates the enumerate object and gets the index and element together. The code is: my_list=[5,10,7,5,6,8,5,15] for index, value in enumerate(my_list): if value == 5: my_list[index] = 9 print(my_list)Output: [9, 10, 7, 9, 6, 8, 9, 15]Find and Replace the Python List Elements With the List Comprehension MethodIn this method, we can generate a new list by applying pre-defined conditions on the old list. The Syntax is: my_list=[5,10,7,5,6,8,5,15] [9 if value==5 else value for value in my_list] print(my_list)Output: [9, 10, 7, 9, 6, 8, 9, 15]Find and Replace the Python List Elements With the map MethodThis method changes the entries of the second list with the index of the first list items. The code is: list_1=[5,10,7] list_2=[7,10,7,5,7,5,10] ent = {k: i for i, k in enumerate(list_1)} result = list(map(ent.get, list_2)) print("list2 after replacement is:", result)Output: list2 after replacement is: [2, 1, 2, 0, 2, 0, 1]
DelftStack articles are written by software geeks like you. If you also would like to contribute to DelftStack by writing paid articles, you can check the write for us page. Related Article - Python List
Given How to replace the element at index i in the list lst with the new element x? Solution IndexingYou 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 ElementsGiven
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 LoopYou 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 LoopA 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 AssignmentStand 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 SolutionI 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']
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 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:
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!! 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. |