Change index in list Python

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.

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 Method

Let’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 Method

We 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 Method

In 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 Method

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

  1. List indexing method is good when we replace one element in a list.
  2. List comprehension method is the right choice when we replace multiple elements in a list based on selective criteria.
  3. Loop methods are discouraged, as it takes more execution time and memory.

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

  • Parse String to List in Python
  • Print Lists in Python
  • Given

    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.

    Change index in list Python

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

    Change index in 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.