7 Efficient Ways to Replace Item in List in Python

Lists in python are data structures used to store items of multiple types together under the same list. Using a list, we can store several data types such as string values, integer, float, sets, nested lists, etc. The items are stored inside square brackets ‘[ ]’. They are mutable data types, i.e., they can be changed even after they have been created. We can access list elements using indexing. In this article, we shall look into 7 efficient ways to replace items in a python list.

How to replace item in list python

Lists are compelling and versatile data structures. As mentioned above, lists are mutable data types. Even after a list has been created, we can make changes in the list items. This property of lists makes them very easy to work with. Here, we shall be looking into 7 different ways in order to replace item in a list in python.

  1. Using list indexing
  2. Looping using for loop
  3. Using list comprehension
  4. With map and lambda function
  5. Executing a while loop
  6. Using list slicing
  7. Replacing list item using numpy

1. Using list indexing

The list elements can be easily accessed with the help of indexing. This is the most basic and the easiest method of accessing list elements. Since all the elements inside a list are stored in an ordered fashion, we can sequentially retrieve its elements. The first element is stored at index 0, and the last element is stored at index ‘len(list)-1’.

Let us take a list named ‘my_list’, which stores names of colors. Now, if we want to replace the first item inside the list from ‘Red’ to ‘Black’, we can do that using indexing. We assign the element stored at the 0th index to a new value. Then the list printed would contain the replaced item.

my_list = ['Red', 'Blue', 'Orange', 'Gray', 'White']
my_list[0] = 'Black'
print(my_list)

Output:

['Black', 'Blue', 'Orange', 'Gray', 'White']

2. Looping using for loop

We can also execute a for loop to iterate over the list items. When a certain condition is fulfilled inside the for loop, we will then replace that list item using indexing.

We shall take the same ‘my_list’ as in the above example. Then, we shall run the for loop for the length of the list ‘my_list’. Inside the loop, we have placed the condition that when the list element equals ‘Orange’, we will replace the item at that index with ‘Black’. Then after the for loop ends, we shall print that list.

my_list = ['Red', 'Blue', 'Orange', 'Gray', 'White']
for i in range(len(my_list)):
  if my_list[i] == 'Orange':
    my_list[i] = 'Black'
print(my_list)

The output prints the list with the replaced value.

['Red', 'Blue', 'Black', 'Gray', 'White']

3. Using list comprehension

List Comprehension in python is a compact piece of code. Using list comprehension, we can generate new sequences from already existing sequences. Instead of writing an entire block of code for executing a for loop or an if-else loop, we can write a single line code for the same.

The syntax for list comprehension is:

[expression for item in list]

It consists of the expression which has to be printed into the new list, the loop statement, and the original list from which the new values will be obtained.

We shall use list comprehension to append the string ‘ color’ to all the list elements of my_list. We shall replace the old values with the updated values.

my_list = ['Red', 'Blue', 'Orange', 'Gray', 'White']
my_list = [(item+' color') for item in my_list ]
print(my_list)

The list with replaced values is:

['Red color', 'Blue color', 'Orange color', 'Gray color', 'White color']

4. With map and lambda function

Map() is a built-in function in python using which we can iterate over an iterable sequence without having to write a loop statement.

The syntax of the map is:

map(function, iterable)

Here, every value inside the iterable will be passed into a function, and the map() function will output the inside function’s return value. Inside the map() function, we have taken a lambda function as the first argument.

A lambda function is an anonymous function containing a single line expression. It can have any number of arguments, but only one expression can be evaluated. Here, the lambda function will append the string ‘ color’ for all the items present in the list and return the new value. Then using the list() function, we shall convert the map object returned by the map() function into a list.

my_list = ['Red', 'Blue', 'Orange', 'Gray', 'White']
my_list = list(map(lambda item: (item +' color'), my_list))
print(my_list)

The output is:

['Red color', 'Blue color', 'Orange color', 'Gray color', 'White color']

If we want to replace a particular item in the list, then the code for that will be:

my_list = ['Red', 'Blue', 'Orange', 'Gray', 'White']
my_list = list(map(lambda item: item.replace("Orange","Black"), my_list))
print(my_list)

We have used the replace() method to replace the value ‘Orange’ from my_list to ‘Black.’ The output is:

['Red', 'Blue', 'Black', 'Gray', 'White']

5. Executing a while loop

We can also have a while loop in order to replace item in a list in python. We shall take a variable ‘i’ which will be initially set to zero. The while loop shall execute while the value of ‘i’ is less than the length of the list my_list. We shall use the replace() method to replace the list item ‘Gray’ with ‘Green.’ The variable ‘i’ shall be incremented at the end of the loop.

my_list = ['Red', 'Blue', 'Orange', 'Gray', 'White']
i = 0
while i < len(my_list):
  my_list[i].replace('Gray','Green')
  i = i + 1
print(my_list)

The updated list is:

['Red', 'Blue', 'Orange', 'Gray', 'White']

6. Using list slicing

We can also perform slicing inside a list. Using slicing enables us to access only a certain part of a list.

The syntax of the list is:

List[ Start : End : Jump ]

Using list slicing, we can replace a given item inside a list. First, we shall store the index of the item to be replaced into a variable named ‘index.’ Then, using list slicing, we will replace that item with a new value, ‘Green.’

my_list = ['Red', 'Blue', 'Orange', 'Gray', 'White']
index = my_list.index('Gray')
my_list = my_list[:index] + ['Green'] + my_list[index+1:]
print(my_list)

The output is:

['Red', 'Blue', 'Orange', 'Green', 'White']

Also, Read | Python Trim Using strip(), rstrip() and lstrip()

7. Replacing list item using numpy

We can also replace a list item using python’s numpy library. First, we will convert the list into a numpy array. Then using numpy’s where() function, we specify a condition according to which we will replace the value. We shall replace the value ‘Gray’ with ‘Green.’ Else, the value will be the same.

import numpy as np
my_list = ['Red', 'Blue', 'Orange', 'Gray', 'White']
my_list = np.array(my_list)
my_list = np.where(my_list == 'Gray', 'Green', my_list)
print(my_list)

The output is:

['Red' 'Blue' 'Orange' 'Green' 'White']

Is there any way to replace items in place?

Using list comprehension, map-lambda function, replace function, etc., we can perform in-place replacement of list items.


This sums up five different ways of replacing an item in a list. If you have any questions in your mind, then let us know in the comments below.

Until next time, Keep Learning!

Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments