0
list1 = ['a','b','c','d']
list2 = [1,0,1,0]

Given two lists like the above, I would like to obtain a third list whose values are ['a','c']

In other words, I'd like the target list to be the values from list1 where the corresponding element in list2 is 1.

1
  • 2
    Try [i for i, j in zip(list1, list2) if j == 1]? Commented Sep 8, 2020 at 1:21

3 Answers 3

1

As noted in the comments:

[i for i, j in zip(list1, list2) if j] would work.

Alternatively, if you were looking for something not so advanced:

list3 = []

for i in range(len(list1)):
    if list2[i] == 1:
        list3.append(list1[i])
Sign up to request clarification or add additional context in comments.

Comments

1

Use enumerate function on second list to include index, which can be used for the first list.

[list1[i] for i, item in enumerate(list2) if item]

Comments

0

Generators can be nice if you have very long lists:

def filterfunc(a, b, keyvalue=1):
    return (x for i, x in enumerate(a) if b[i] == keyvalue)

To get the whole sequence:

list(filterfunc(a, b))

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.