Python Program to Replace Elements in a List


In python, multiple items can be kept in a single variable by using lists. One of the four built-in data types in Python for storing data collections is the list the other three are the tuple, set, and dictionary, each of which has a unique purpose.

What is List?

Square brackets are used to build lists. The most effective tool in Python is the list because they don't necessarily have to be homogeneous. DataTypes like Integers, Strings, and Objects can all be found in one list. Because lists are mutable, changes can be made to them even after they have been created.

Python lists' ability to include duplicate values is one of their main features. This allows us to loop through the list's items and determine each one's value. If the value is one that has to be replaced, we do so.

In this article, we will be learning about six methods of replacing elements in a list by using python program.

Using For Loop

Python's for loop is used to iterate over an iterable like a String, Tuple, List, Set, or Dictionary in a sequential manner. So, for loop we will use here, will iterate over the given list and replace the values or elements from the list. For example we take two elements such as ‘Coffee’ and ‘Tea’ in the list. Now, we want to replace them with ‘Fruit juice’ and ‘Lime soda’. For completing the task we will use for loop and if condition for replacing the elements.

Algorithm

  • First define the list.

  • Using for loop create a range that is the list of elements to be iterated through.

  • Using if statement, replace the elements.

  • Print the list in the output.

Example

In the following program, a list of elements is defined. Then, for each element in the list, an if statement checks to see if it matches either 'Coffee' or 'Tea'.

If so, that element is replaced with either 'Fruit juice' or 'Lime soda', respectively. Finally, the new list is printed.

# First define a list of elements
list_1 = ['Coffee', 'Sting', 'Maza', 'Tea', 'Tea']
for i in range(len(list_1)):
   
   # if statement for replacing elements
   if list_1[i] == 'Coffee':
      list_1[i] = 'Fruit juice'
   # if statement for replacing elements
      if list_1[i] == 'Tea':
         list_1[i] = 'Lime soda'
print(list_1)

Output

['Fruit juice', 'Sting', 'Maza', 'Lime soda', 'Lime soda']

Using List Indexing

The list's entries can be accessed using indexing. The simplest and most straightforward way to replace elements inside a list in Python is to use this. Utilizing index 0, we can change the first item on the list.

In the example below, the new value is a value that should replace the previous value in the list, and the index is the index of the item that we want to change.

Syntax

list_1[index]= Replaced value
(Replaced value= new value)

Algorithm

  • First define the list.

  • Replace the value by using the index number.

  • Print the list in the output.

Example

The following program replaces an element in a list. The original list included "TV", "STD", and "WIFI". The second element, "STD", is replaced with the value "cell phone" after the full list is printed.

# first define a list of elements
list_1 = ['Television', 'STD', 'WIFI']

# replacing elements using index
list_1[1]= 'Mobile phone'
print(list_1)

Output

['Television', 'Mobile phone', 'WIFI']

Using The While Loop

To replace values in the list, we may alternatively use a while loop. For loop's work is repeated by the while loop. We define a variable with the value 0 and run over the list in the while loop first. If value matches the value we wish to change, the old value is replaced.

Algorithm

  • First define the list.

  • Define a variable.

  • Apply the while loop.

  • If the variable value matches the value in list it will replace the element.

  • Print the list in the output.

Example

In the following program, a list of four elements is created. A while loop iterates over the items in the list and if an item is equal to 'VIVO', it will be replaced with 'OPPO'. The modified list is then printed.

# first define a list
list_1 = ['REALME', 'REDME', 'APPLE', 'VIVO']
i = 3
while i < len(list_1):

   # replace VIVO with OPPO from the list
   if list_1[i] == 'VIVO':
      list_1[i] = 'OPPO'
   i += 1
print(list_1)

Output

['REALME', 'REDME', 'APPLE', 'OPPO']

Using List Slicing

In Python, you must slice a list in order to access a specific subset of its elements. Use of the colon, a simple slicing operator, is one method for accomplishing this (:). With the help of this operator, one can declare the step as well as the starting and ending points for the slicing. From the original list, list slicing produces a new list.

Syntax

list_1 = list_1[: index]+[‘N_V’]+list_1[index+1:]
 *(N_V= new value)

Algorithm

  • First define the list

  • Next step is to find the index of the replacing element

  • Replace the element using list slicing.

  • Print the list in the output.

Example

Here, Python gives us the option to slice across a list. We can access some of the list's components due to slicing. Slicing allows us to replace elements inside the list. We start by locating the variable's index that we wish to replace and storing it in variable "i."

Then, using list slicing, we swap out that item for a fresh value. If we wish to swap out "Replication" with "Radiation" we must first identify the index of "Replication" then perform list slicing to take out "Replication" and replace it with "Radiation".

list_1 = ['Heat', 'Replication', 'Induction', 'Conduction', 'Precipitation']
i = list_1.index('Replication')
list_1 = list_1[:i]+['Radiation']+list_1[i+1:]
print(list_1)

Output

['Heat', 'Radiation', 'Induction', 'Conduction', 'Precipitation']

Using Lambda Function

The anonymous nature of Python Lambda Functions indicates that they lack a name. As we already know, a standard Python function is defined using the def keyword. Similar to this, Python uses the lambda keyword to define an anonymous function.

There is only one expression that is evaluated and returned in this function, regardless of the number of parameters.

Lambda functions can be used anywhere that function objects are required. The fact that lambda functions are syntactically limited to a single expression must always be kept in mind.

Syntax

list_1=list(map(lambda x: x.replace(‘O_V’,’N_V’),list_1))

Algorithm

  • Define a list.

  • Replace the values using lambda and map function.

  • Print the list as output.

Example

Here, to replace the element in the list using this way, we use the lambda and map functions. Python has a built-in method called map() that allows you to loop through a list without using a loop statement.

As a requirement to replace value, we provided one expression here. Here, in the lambda function, we swap out "Replication" for "Radiation." The map object is then transformed into the list using the list() function.

list_1 = ['Heat', 'Replication', 'Induction', 'Conduction', 'Precipitation']
list_1 = list(map(lambda x: x.replace('Replication', 'Radiation'), list_1))
print(list_1)

Output

['Heat', 'Radiation', 'Induction', 'Conduction', 'Precipitation']

Conclusion

In this article, we have briefly explained five different ways of replacing the elements using python language.

Updated on: 24-Apr-2023

660 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements