0

this is my code;

list = ["abc-123", "abc-456", "abc-789", "abc-101112"]
all_ABCs = [s for s in list if "abc" in s]
x = len(all_ABCs)
print("There are " + x + " items with 'abc' in the list")
print(all_ABCs[0])

   for x in all_ABCs:
   del all_ABCs[0]
   print(all_ABCs[0])

This is my code with outcome;

There are 4 items with 'abc' in the list
abc-123
abc-456
abc-789

I am trying to make a loop that prints out the first item of the list every time. And when there are no more items in the list the for loop has to stop. This isn't working right now as you can see, the last abc isn't printed out.

2 Answers2

1

Basically for loop is not the right kind of loop to use in this case. It can be done, but it's better to use while loop:

spam = ["abc-123", "abc-456", "abc-789", "abc-101112", 'noabc-1234']
abcs = [item for item in spam if item.startswith('abc')]
print(f"There are {len(abcs)} items with 'abc' in the list")
print(abcs)
while abcs:
    print(abcs.pop(0))

Now, there is the question why remove the item just to print it. This is not necessary. You can simply iterate over list (using for loop) and print items or if all elements are strings, use print('\n'.join(abcs)).

buran
  • 13,682
  • 10
  • 36
  • 61
0

Let's start with cutting straight to the chase:

my_list = ["abc-123", "345-abc", "345", "abc-456", "abc-789", "abc-101112", "and-123"]
all_ABCs = [s for s in my_list if "abc" in s]
x = len(all_ABCs)
print(f"There are {x} items with 'abc' in the list")

for _ in range(x):
   first_item = all_ABCs.pop(0)
   print(first_item)

Output:

There are 5 items with 'abc' in the list
abc-123
345-abc
abc-456
abc-789
abc-101112

And now for some notes:

  1. You don't see the last item because you delete it before you want to print it. Use pop instead of del.

  2. You are iterating over a list that is changing during the loop. Iterate over the length of the list, and not the list itself.

  3. You are calling your list list which is a reserved word in Python, for, well, lists, this is generally bad practice and I recommend using list_ instead, read this for more information on underscores in Python.

DalyaG
  • 2,979
  • 2
  • 16
  • 19