Comparing two lists in Python

Question:

I have two lists sol1 and cond1. I want to compare these two lists and print values from sol1 corresponding to False in cond1. For instance, False occurs at cond1[0],cond1[2] and the corresponding values are sol1[0],sol1[2]. I present the expected output.

sol1 = [1, 2, 4, 6, 7]
cond1 = [False, True, False, True, True]

The expected output is

[1,4]
Asked By: AEinstein

||

Answers:

By using zip you can iterate over pairs of items, and use a list comprehension to filter out True values:

sol1 = [1, 2, 4, 6, 7]
cond1 = [False, True, False, True, True]

result = [value for value, condition in zip(sol1, cond1) if not condition]
print(result)
>>> [1, 4]
Answered By: Adid

Just loop through the cond1 list and check if the value of the current index is False if yes used the index and append the corresponding value of sol1 list to the output list.

Note: This only works when the two lists are of the same length.

Solution

sol1 = [1, 2, 4, 6, 7]
cond1 = [False, True, False, True, True]
output = []

for idx, val in enumerate(cond1):
    if val is False:
        output.append(sol1[idx])

print(output)
Answered By: Maxwell D. Dorliea
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.