Replacing List Elements Using Comprehension and Conditional Expressions
Searching and replacing elements in a list is a common programming task. To achieve this, leverage the power of list comprehension along with a conditional expression.
Consider a list of integers as an example:
a = [1, 2, 3, 4, 5, 1, 2, 3, 4, 5, 1]
Our objective is to replace all occurrences of 1 with 10 within the list. Using list comprehension and a conditional expression, we can create a new list with the desired replacements:
[4 if x == 1 else x for x in a]
In this expression, we iterate through each element x in the list a. If x is equal to 1, it is replaced with 4; otherwise, it remains unchanged. The result is a new list with all 1s replaced with 4s:
[4, 2, 3, 4, 3, 2, 4, 4]
Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.
Copyright© 2022 湘ICP备2022001581号-3