Python Forum

Full Version: While loop with condition that a list of strings contain a substring
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Let's say that I have
li = ['A1','B','A2','C']
How would I go about coding a while loop that runs while li contains 'A'?
check itertools.takewhile()
On second reading, can you elaborate what you mean exactly... i.e. in your example what is expected behaviour?
So if I have
li = ['A','B','A','C']
while 'A' in li: 
    print(li.pop(0))
It should print A B A C.

But if I have
li = ['A1','B','A2','C']
while 'A' in li: 
    print(li.pop(0))
Nothing prints. But what I want it to do is check if a substring of one of the elements contains 'A', such as in 'A1'.
First of all, your first snippet will not print A B A C, but just A B A (each on separate line)
Next, you need to change second snippet to
li = ['A1','B','A2','C']
while any('A' in item for item in li): 
    print(li.pop(0))
Output:
A1 B A2
Finally, use collections.deque for memory efficient pop from either end.

from collections import deque
de = deque(['A1','B','A2','C'])
while any('A' in item for item in de): 
    print(de.popleft())
Thanks, it works!