replace list item python code example

Example 1: change element in list python

list = ['unchanged', 'unchanged']
list[0] = 'changed'
print(list)
## ['changed', 'unchanged']

Example 2: Python - Change List Items

thislist = ["apple", "banana", "cherry"]
thislist[1] = "blackcurrant"
print(thislist)

Example 3: how to replace number in list python

>>> numbers = [1 , 2, 3, 4, 4, 6] # a normal python list 
>>> numbers[4] = 5 # replace the redundant item (5th item) 
>>> numbers 
[1, 2, 3, 4, 5, 6]

Example 4: how to replace an element of a list using list comprehension

new_list = ["A" if element == "a" else element for element in a_list]