1

I have two lists of the same size, one is a list of strings, and the other a list of booleans (True, False) and I want to return a list of strings only if the index is True.

b_list = [True, False, True]
s_list = ['abc', 'sfsfsfsf', 'def']

want

s_list = ['abc','def'] 

2 Answers 2

5

Use itertools.compress

compress(data, selectors): Return data elements corresponding to true selectors elements

So s_list is data and b_list is selectors:

In [8]: import itertools

In [9]: list(itertools.compress(s_list, b_list))
Out[9]: ['abc', 'def']
Sign up to request clarification or add additional context in comments.

Comments

2

Without itertools using list comprehension:

[y for (x,y) in zip(b_list, s_list) if x]

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.