How to replace a specified value in a list in Python?

You can use list comprehensions and conditional expressions to replace specific values in a list. Here is an example:

# 原始列表
my_list = [1, 2, 3, 4, 5]

# 替换值为2的元素为10
new_list = [10 if x == 2 else x for x in my_list]

print(new_list)  # 输出:[1, 10, 3, 4, 5]

In the given example, a list comprehension is used to iterate over each element in the original list. If an element has a value of 2, it is replaced with 10; otherwise, it is kept as is. Finally, the new elements are added to a new list.

You can modify the conditional expression according to your needs to substitute different values.

bannerAds