Search code examples
pythonlistletter

How to find out whether a list contains any letters


I have a list that I am trying to get a false return on if it contains any letters. When I get to the list that is as follows:

list = ['1', '+', 'b1'] 

I try to run

any(characters.isalpha() for characters in list)

but it is returning False, even though list[2] clearly contains a letter.

So I tried to do the following, thinking that I might not have properly iterated over each item in list:

for characters in list:
  any(characters.isalpha() for char in characters)

which returns

False
False
False

I'm at a loss for how to get the program to pick up that there is a letter and return True for a query about whether list contains any letters. If you could help me figure the answer to that I would greatly appreciate it.


Solution

  • You need another for ... in ... clause to iterate over each character in each string:

    >>> lst = ['1', '+', 'b1']
    >>> any(char.isalpha() for string in lst for char in string)
    True
    >>>
    

    for char in string takes each string returned by for string in lst and iterates over its characters.