Reputation: 127
How can I create a list C based on two list A and B using list comprehension, where C list contains an item from A just when items in B is TRUE
. My for loop
implementation is here:
A = ["ID","population","median_age"]
B = [False False True]
C = []
for x in range(len(A)):
if B[x] == True:
C.append(A[x])
Upvotes: 0
Views: 70
Reputation: 35927
You could do something like this:
C = [a for a, b in zip(A, B) if b]
Doing something like for i in range(len(lst))
is rarely idiomatic in Python, as you'd usually prefer to do for i, value in enumerate(lst)
. But in this case, using zip
seems both safer and more idiomatic as it manages cases where A
and B
are of different lengths.
Upvotes: 5