Conditionally replace values in a Python list
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:
|
1 2 3 4 5 6 |
if __name__ == '__main__': a = [1, 2, 3, 4, 5, 6, 7, 8, 9] a = [0 if x % 2 == 1 else x for x in a] print(a) # prints [0, 2, 0, 4, 0, 6, 0, 8, 0] |
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:
|
1 2 3 4 5 6 7 8 9 10 |
if __name__ == '__main__': a = [1, 2, 3, 4, 5, 6, 7, 8, 9] for i, v in enumerate(a): if v % 2 == 1: # odd indices a[i] = 0 print(a) # prints [0, 2, 0, 4, 0, 6, 0, 8, 0] |
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.
|
1 2 3 4 5 6 7 |
if __name__ == '__main__': a = [1, 2, 3, 4, 5, 6, 7, 8, 9] a = list(map(lambda x: 0 if x % 2 == 1 else x, a)) print(a) # prints [0, 2, 0, 4, 0, 6, 0, 8, 0] |
That’s all about conditionally replace values in a list in Python.
Thanks for reading.
To share your code in the comments, please use our online compiler that supports C, C++, Java, Python, JavaScript, C#, PHP, and many more popular programming languages.
Like us? Refer us to your friends and support our growth. Happy coding :)