2

Can anyone help me understand the following piece of python code:

for i, char in filter(lambda x: x[1] in str1, enumerate(str2)):
    # do something here ...

str1 and str2 are strings, I sort of understand that the "lambda x: x[1] in str1" is filtering condition, but why x[1] ?

How can I convert this for loop into a lower level (but easier to understand) python code ?

Thanks

1
  • enumerate returns an iterable object contain the indices and items, so the x would be a tuple contain each element with its index and x[1] is the item (character) itself. Commented Aug 26, 2016 at 22:03

2 Answers 2

4

This appears functionality equivalent to:

for i, char in enumerate(str2):
    if char in str1:
        # do something here

filter is taking a list of tuples consisting of the index and elements of str2, filtering out those elements that do not appear in str1, then returning a iterable of the remaining indices and elements from str2.

Sign up to request clarification or add additional context in comments.

Comments

0

Because of enumerates.

Enumerates returns tuples of (index, value) for an iterable of values.

x is a tuple of index, char.

I would write lambda (index, char): char in str1 for clarity

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.