Q:

Passing the iterating variable inside loop body

I'm new to Python and am confronted with the following (hopefully simple) problem.
I want to check some condition with an iterator over a list and would like to get the element for which this is fulfilled.
str = "abab"
symbols = ["a", "b"]
while any(letter in str for letter in symbols):
        #print or do something else with the letter

Naturally, after attempting to use the loop variable in the body, it doesn't exist anymore and the compiler throws an error. So, how can I pass the current element of symbols inside the while-loop?
Thanks in advance.

A:

Try this:
string = "abab"
symbols = ["a", "b","c"]
for letter in (letter for letter in symbols if letter in string):
    print(letter)

By the way, try to avoid naming your variable str (it's a Python built-in).

