This post will discuss how to conditionally replace values in a list in Python.

1. Using List Comprehension

The most Pythonic solution is to use a list comprehension, which can construct a new list whose each element results from some operation applied to each member of an iterable.

Here’s a working example where each odd element in the list is replaced by value 0:

Download  Run Code

2. Using enumerate() function

You can also use the enumerate() function to retrieve the position index and corresponding value at the same time while looping through a list.

Here’s a working example where we have used the value to check for odd element and its index to update the value if required:

Download  Run Code

3. Using map() function

This can also be done using Python’s built-in function map() and lambda expression. Note that map() is obsolete and considered unpythonic as it duplicates the features of generator expressions.

Download  Run Code

That’s all about conditionally replace values in a list in Python.