Home » How to Replace Values in a List in Python

How to Replace Values in a List in Python

by Erma Khan

Often you may be interested in replacing one or more values in a list in Python.

Fortunately this is easy to do in Python and this tutorial explains several different examples of doing so.

Example 1: Replace a Single Value in a List

The following syntax shows how to replace a single value in a list in Python:

#create list of 4 items
x = ['a', 'b', 'c', 'd']

#replace first item in list
x[0] = 'z'

#view updated list
x

['z', 'b', 'c', 'd']

Example 2: Replace Multiple Values in a List

The following syntax shows how to replace multiple values in a list in Python:

#create list of 4 items
x = ['a', 'b', 'c', 'd']

#replace first three items in list
x[0:3] = ['x', 'y', 'z']

#view updated list
x

['x', 'y', 'z', 'd']

Example 3: Replace Specific Values in a List

The following syntax shows how to replace specific values in a list in Python:

#create list of 6 items
y = [1, 1, 1, 2, 3, 7]

#replace 1's with 0's
y = [0 if x==1 else x for x in y]

#view updated list
y

[0, 0, 0, 2, 3, 7]

You can also use the following syntax to replace values that are greater than a certain threshold:

#create list of 6 items
y = [1, 1, 1, 2, 3, 7]

#replace all values above 1 with a '0'
y = [0 if x>1 else x for x in y]

#view updated list
y

[1, 1, 1, 0, 0, 0]

Similarly you could replace values that are less than or equal to some threshold:

#create list of 6 items
y = [1, 1, 1, 2, 3, 7]

#replace all values less than or equal to 2 a '0'
y = [0 if x#view updated list
y

[0, 0, 0, 0, 3, 7]

Find more Python tutorials here.

Related Posts