1

I have two list listOne & listTwo

e.g.

listOne could contain 'about', 'day', 'school'

listTwo could contain 'a','c','da','z'

I want to find out all the elements in listOne which start with characters from elements in listTwo. The output with above example is 'about' and 'day'

I try to implement it with following code:

for elem1 in listTwo:
    for elem2 in listOne:
        if elem2.startswith(elem1):
            result.append(elem2)

but I feel it nested too much. Is there a more elegant way to achieve it in Python?

2 Answers 2

1

The way that you're doing it is fine. It's easy to read/understand, etc.

However, if you really want, you can probably condense it down using itertools.product:

from itertools import product
result = [elem2 for elem1, elem2 in product(listTwo, listOne) if elem2.startswith(elem1)]
Sign up to request clarification or add additional context in comments.

5 Comments

Thanks! That's what I am looking for. Where should I do the result.append(elem1)?
@Leem.fin -- You don't need it. Just assign the list comprehension to result...
I run the code, the output is ['a', 'da'], but I need ['about', 'day']
@Leem.fin -- Then the code in your question is incorrect... You're appending elem1 which comes from listTwo which doesn't have those words in it... However, the fix is easy. Just change the first elem1 to elem2 and you're golden.
I think it's confusing that elem1 is drawn from listTwo and elem2 is drawn from listOne, but I do acknowledge is that this is exactly what the OP did in his question. :-}
1

You can pass a tuple to str.startswith method.

From the doc:

str.startswith(prefix[, start[, end]]): Return True if string starts with the prefix, otherwise return False. prefix can also be a tuple of prefixes to look for. With optional start, test string beginning at that position. With optional end, stop comparing string at that position.

But this is supported in Python 2.5+

tuple_listTwo = tuple(listTwo)

[ele for ele in listOne if ele.startswith(tuple_listTwo)]

Output:

['day', 'about']

3 Comments

Also, depending on the list sizes, you'll be a lot more efficient if you create the tuple first (otherwise, you're recreating the same tuple over and over and over).
@mgilson,regarding your first comment, I think you had this notion based on OP's code. But I read the description and did this.
Yeah, I've redacted my first comment. OP had the wrong code, but edited it to get the solution you've posted.

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.