Search code examples
pythonlistpython-3.xany

Why does this generator expression raise a syntax error?


This line throws an error saying I didn't define x even though I stated that x is an element of the list:

any(i.isdigit() for i in x for x in [name.id for name in all.names])

So x is a string element of the list, and I am checking if for some character in each element x, that element x contains a number using .isdigit(). How come this doesn't work?


Solution

  • Comprehensions/generator expressions in Python nest from left to right (yeah, it can be a bit confusing). Swap them:

    for x in [name.id for name in all.names] for i in x
    

    Or separate out for clarity:

    def contains_digit(s):
        return any(c.isdigit() for c in s)
    
    
    any(contains_digit(name.id) for name in all.names)