'Compare two lists and modify element if different
I want to create a new list by comparing two equal sized lists and keeping the value if they match, and setting it to a fixed value if they don't. For example, if I compared the following two lists with a fixed value of -1:
fixed_value = -1
a = [1,2,3,4,5]
b = [1,3,3,2,5]
The output here should be [1, -1, 3, -1, 5].
Is there any neat way to do so, perhaps using a list comprehension?
Solution 1:[1]
You can use zip() and a list comprehension.
fixed_value = -1
a = [1,2,3,4,5]
b = [1,3,3,2,5]
result = [item1 if item1 == item2 else fixed_value for item1, item2 in zip(a, b)]
print(result) # Prints [1, -1, 3, -1, 5]
zip() produces an iterable of tuples, where the first element is (a[0], b[0]), the second is (a[1], b[1]), etc. Then, we can check the elements in these tuples for equality; if they're equal, we add the first element in our tuple to the list, else we output -1.
Solution 2:[2]
You could use list comprehension and include an if statement to check your condition. This solution uses zip() to iterate both lists at the same time. zip() is a Python built-in is able to "(i)terate over several iterables in parallel, producing tuples with an item from each one.":
result = [
a_element if a_element == b_element else fixed_value
for a_element, b_element in zip(a, b)
]
Iterating both a and b at the same time, you compare the elements. If they're the same, just use one of them (they're equal), but in other case use your fixed_value.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | BrokenBenchmark |
| Solution 2 |
