Python Forum
While loop with condition that a list of strings contain a substring
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
While loop with condition that a list of strings contain a substring
#1
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'?
Reply
#2
check itertools.takewhile()
On second reading, can you elaborate what you mean exactly... i.e. in your example what is expected behaviour?
If you can't explain it to a six year old, you don't understand it yourself, Albert Einstein
How to Ask Questions The Smart Way: link and another link
Create MCV example
Debug small programs

Reply
#3
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'.
Reply
#4
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())
If you can't explain it to a six year old, you don't understand it yourself, Albert Einstein
How to Ask Questions The Smart Way: link and another link
Create MCV example
Debug small programs

Reply
#5
Thanks, it works!
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  unable to remove all elements from list based on a condition sg_python 3 460 Jan-27-2024, 04:03 PM
Last Post: deanhystad
  extract substring from a string before a word !! evilcode1 3 554 Nov-08-2023, 12:18 AM
Last Post: evilcode1
  How to read module/class from list of strings? popular_dog 1 486 Oct-04-2023, 03:08 PM
Last Post: deanhystad
  Trying to understand strings and lists of strings Konstantin23 2 778 Aug-06-2023, 11:42 AM
Last Post: deanhystad
  problem in using int() with a list of strings akbarza 4 718 Jul-19-2023, 06:46 PM
Last Post: deanhystad
  Delete strings from a list to create a new only number list Dvdscot 8 1,556 May-01-2023, 09:06 PM
Last Post: deanhystad
  [SOLVED] [regex] Why isn't possible substring ignored? Winfried 4 1,078 Apr-08-2023, 06:36 PM
Last Post: Winfried
  Help with Logical error processing List of strings dmc8300 3 1,096 Nov-27-2022, 04:10 PM
Last Post: Larz60+
  ValueError: substring not found nby2001 4 7,965 Aug-08-2022, 11:16 AM
Last Post: rob101
  Match substring using regex Pavel_47 6 1,457 Jul-18-2022, 07:46 AM
Last Post: Pavel_47

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020