Python Replace list element using List comprehension

In this program, we are going to understand how to Replace list elements in Python using List comprehension. There are many ways to iterate through the list, the most popular is for loop but choosing a list compression over for loop makes our code space-efficient and has fewer lines of code.

Syntax

reslist = [expression for item in iterable if condition == True]

Parameters

  • expression: It represents the current item in the list or output.
  • iterable: It represents the iterable object in python list, tuple, set.
  • condition: It is a filter that filters values that pass where values == True.

return

It returns a new list leaving the original list unchanged.

Python program Replace list element using List comprehension


In this Python program, we have used the list comprehension to replace values with conditions where element == ‘data’ replaced it with ‘date’ and returned a new updated_list.

#Python3 program to Replace list elemnt using list comprehension


original_list = ['C#', 'Java', 'Rust', 'seaborn', 'data', 'date']
updated_list = ['date' if element == 'data' else element for element in original_list ]
print(updated_list)

Output

['C#', 'Java', 'Rust', 'seaborn', 'date', 'date']

Python program to Replace nested list element/multidimensional list


In this Python program, we are using list compression to replace elements in a nested list or multidimensions lists based on conditions.

The statement work for [‘date’ if element == ‘data’ else element for element in innerlst] to iterate over inner list and replace elements.

The statement “for innerlst in original_list” is for the whole list

#Python3 program to Replace nested list elemnt using list comprehension


original_list = [['C#', 'Java', 'Rust'], ['seaborn', 'data', 'date'],['data','C#','C']]



updated_list = [['date' if element == 'data' else element for element in innerlst  ] for innerlst in original_list]

print(updated_list)



Output

[['C#', 'Java', 'Rust'], ['seaborn', 'date', 'date'], ['date', 'C#', 'C']]