-1

Say I have a list of strings, mylist, from which I want to extract elements that satisfy a condition in a another list, idx:

mylist = ['a','b','c','d']


idx = ['want','want','dont want','want']

What I want as output is:

['a','b','d']

which is a list of elements that I 'want'

How can this by done?

1
  • [mylist[i] for i,x in enumerate(idx) if x == 'want'] Commented Feb 5, 2018 at 17:30

1 Answer 1

2

You can use zip to stride through your two lists element-wise, then keep the elements from mylist if the corresponding element from idx equals 'want'

>>> [i for i, j in zip(mylist, idx) if j == 'want']
['a', 'b', 'd']
Sign up to request clarification or add additional context in comments.

1 Comment

This is perfect. Thanks Cory!

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.