Replace Item in Python List

Posted in /  

Replace Item in Python List
vinaykhatri

Vinay Khatri
Last updated on December 18, 2024

    There are many ways to replace item or items from a Python list. We can use indexing, list comprehension, for loop, and map() function, to change single or multiple values from a Python list. There can be many scenarios where you want to replace single or multiple elements from a Python list. In that, you must know all the techniques to do so. In this Python tutorial, we will walk through the different ways to replace or change a list element from a Python list.

    Overview

    Here is the list of techniques we will learn to change the single or multiple values from the Python list.

    1. List Indexing and slicing: It is the basic way of accessing and changing the value of a Python list.
    2. List Comprehension: It is a shorthand technique to create a new list from an existing list using a single line Python statement.
    3. For loop: Using for loop we can iterate over the list elements, and look out for the different elements that we want to change.
    4. map function: With the help of the map function we can apply a function on every element of the Python list and replace the values of list elements.

    Python Replace List Elements: Using List Indexing and Slicing

    Python lists support indexing and slicing, which allow us to access individuals or a series of elements from a Python list. Not only accessing we can also use the indexing and slicing operation with the assignment operator to new values to the existing list elements. With the help of Python list indexing, we can access and replace a list element. For example, let say we have a Python list recharge_plans that contains the price for the different Recharge Plans.

    recharge_plans = [149, 250, 399, 599, 999]
    

    Now due to some change in business strategy company decide to rise the first plan price by 10% . In that case, now you need to change the price of the first element, to do so the best approach would be using the Python list indexing.

    recharge_plans = [149, 250, 399, 599, 999]
    
    #replace the first element of the recharge_plan using indexing
    
    recharge_plans[0] = recharge_plans[0] + (10*recharge_plans[0])/100
    
    print(recharge_plans)

    Output

    [163.9, 250, 399, 599, 999]

    We can also use list slicing to replace the multiple elements from a Python list. Example Now let's increase the price of the first 3 elements of recharge_plans by 10 % using list slicing.

    recharge_plans = [149, 250, 399, 599, 999]
    print("Initial Recharge Plans: ", recharge_plans)
    
    # new value for first element 
    first =recharge_plans[0] + (10*recharge_plans[0])/100
    
    # new value for second element 
    second =recharge_plans[1] + (10*recharge_plans[1])/100
    
    # new value for third element 
    third = recharge_plans[2] + (10*recharge_plans[2])/100
    
    #replace the firt three elements of the recharge_plan using slicing
    recharge_plans[0:3] = [first, second, third]
    
    print("Recharge Plans After 10% increment: ",recharge_plans)
    

    Output

    Initial Recharge Plans: [149, 250, 399, 599, 999]
    Recharge Plans After 10% increment: [163.9, 275.0, 438.9, 599, 999]

    Although with List slicing we can replace the multiple elements, still we can end up using repetitive logic to create new values, as we are doing in the above example. The logic for adding 10% increment is the same, but we need to store those values in a list when we are assigning them to the list slicing. So it's always a better approach to use for loop, list comprehension or map() function when replacing multiple values in a Python list.

    Python Replace List Elements: Using a List Comprehension

    List Comprehension provides a single line code syntax to create a new list out of an existing one. We can also use list comprehension when we wish to replace multiple or all the elements from a Python list. Example 1 In this example, we will use the List comprehension and replace all the elements from our recharge_plans .

    recharge_plans = [149, 250, 399, 599, 999]
    print("Initial Recharge Plans: ", recharge_plans)
    
    '''
    replace all the elements from the recharge_plane list using list comprehension
    with 10% increment in every element value
    '''
    recharge_plans = [(element+(element*10)/100) for element in recharge_plans]
    
    print("Recharge Plans After 10% increment: ",recharge_plans)

    Output

    Initial Recharge Plans: [149, 250, 399, 599, 999]
    Recharge Plans After 10% increment: [163.9, 275.0, 438.9, 658.9, 1098.9]

    In the above example, we used the list comprehension to replace every element from the recharge_plans with 10% of increment. But we can also use the if..else statement with the list comprehension if we only wish to replace specific elements. syntax

    list_name = [new_element if condition else new_element for index, element enumerate(exist_list) ]

    Example 2 Let's use the list comprehension and only replace the 2nd and 3rd elements from the recharge_plans list. To do that we also need to use Python enumerate , which will help us to access the index value of the element.

    recharge_plans = [149, 250, 399, 599, 999]
    print("Initial Recharge Plans: ", recharge_plans)
    
    '''
    replace only 1st and 2nd elements from the recharge_plane list using list comprehension
    with 10% increment 
    '''
    recharge_plans = [(element+(element*10)/100) if index == 0 or index==1 else element for index, element in enumerate(recharge_plans) ]
    
    print("Recharge Plans After 10% increment: ",recharge_plans)
    

    Output

    Initial Recharge Plans: [149, 250, 399, 599, 999]
    Recharge Plans After 10% increment: [163.9, 275.0, 399, 599, 999]

    Python Replace List Elements: Using For Loop

    Although using list comprehension we can replace multiple elements from a list, but with multiple conditions, the statement could be clustered and hard to understand with one go. So when we have multiple conditions we should prefer using for loop instead of list comprehension. With for loop , we can iterate over the list elements, but when it comes to changing or replacing the values we need the index number of the element. So to loop with indexes in Python we use the enumerate function. Example

    recharge_plans  = [149, 250, 399, 599, 999]
    print("Initial Recharge Plans: ", recharge_plans)
    
    '''
    replace only 1st and 2nd elements from the recharge_plane list using for loop
    with 10% increment.
    '''
    for index, element in enumerate(recharge_plans):
        # replace the value of 0 and 1 index position elements
        # by incresing them 10%
        if index in (0,1):
            recharge_plans[index] = element+ (element*10)/100
    
    print("Recharge Plans After 10% increment: ",recharge_plans)
    

    Output

    Initial Recharge Plans: [149, 250, 399, 599, 999]
    Recharge Plans After 10% increment: [163.9, 275.0, 399, 599, 999]

    Python Replace List Elements: Using Python Map Function

    With the Python map function , we can perform a similar operation on all the Python list elements. We can leverage this property of the Python map function and replace the specific or all the elements from a Python list. Example Now let's use the map function and replace the 3rd and 4th values of recharge_plans by increasing them 10%.

    def increment_10(index, element):
        # replace the value of 2 and 3 index position elements
        # by increasing them 10%
        if index in (2,3):
            return element+ (element*10)/100
    
        # if the index value is not 2 or 3
        # value will remain the same
        return element
    
    recharge_plans  = [149, 250, 399, 599, 999]
    indices = range(len(recharge_plans))
    
    print("Initial Recharge Plans: ", recharge_plans)
    
    '''
    replace only 3rd and 4th elements from the recharge_plane list using map
    with 10% increment.
    '''
    recharge_plans = list(map(increment_10, indices, recharge_plans))
    
    print("Recharge Plans After 10% increment: ",recharge_plans)
    

    Output

    Initial Recharge Plans: [149, 250, 399, 599, 999]
    Recharge Plans After 10% increment: [149, 250, 438.9, 658.9, 999]

    Wrapping Up!

    In this tutorial, we learned how to replace the list elements in Python using different techniques. With the index, slicing and for loop techniques we replace the list elements without creating a new list, in these techniques, we perform the in-place list element replacing. But with list comprehension and map() functions we create a new list using the existing list and assign the new list values to the existing list name, this also does the trick, but behind the scene, we are creating a new list, using extra space. People are also reading:

    Leave a Comment on this Post

    0 Comments