Reputation: 45
I'm reading a series of values, like 4, 5, 5, 6, 6, 6, 7, 6, 4, 5, 6, 7, 6, 5
The first value will always be 4 and others will always be >4 until another 4 is reached. I want to continue the loop, but stop before the next 4 is reached.
So my desired output would be: 4, 5, 5, 6, 6, 6, 7, 6
for value in list:
print(value)
I'm sure it's simple, but I can't think of the logic to stop the loop
for value in list:
print(value)
if value == 4:
break
If I do this, it stops at the first 4 of course. How do I get the logic to ignore the first 4 and only apply that if value == 4, after the first loop cycle?
Upvotes: 0
Views: 106
Reputation: 117
Use a counter:
num_4s = 0
for value in list:
if value == 4:
num_4s += 1
if num_4s > 1:
break
print(value)
This would probably even help someone who has to count more than one original value before stopping.
Upvotes: 1
Reputation: 2438
If your stopping condition don't depend on the first element of the list, you can just skip it.
print(list[0])
for value in list[1:]:
if value == 4:
break
print(value)
If for example, you wanted to design this in a way where your stopping condition depends on the first item, you can do:
stop_value = list[0]
print(stop_value)
for value in list[1:]:
if value == stop_value:
break
print(value)
Upvotes: 0
Reputation: 3233
I think this can be done without for loop like this :
l = [4, 5, 5, 6, 6, 6, 7, 6, 4, 5, 6, 7, 6, 5]
print(l[:l[1:].index(4) +1])
Upvotes: 0
Reputation: 114
I suppose there are multiple options, which one is 'correct' would depend on your exact use case. You could skip the first element within your loop:
print(data[0])
for value in data[1:]:
if value == 4:
break
print(value)
You could also add an additional check for the index:
for i, value in enumerate(data):
if value == 4 and i > 0:
break
print(value)
Upvotes: 1
Reputation: 2267
another solution
l = [4, 5, 5, 6, 6, 6, 7, 6, 4, 5, 6, 7, 6, 5]
f = None
idx = 0
while l[idx] not in (f,):
f = l[0]
print (l[idx])
idx += 1
Upvotes: 1
Reputation: 989
This is the solution you may help you.
n = [4, 5, 5, 6, 6, 6, 7, 6, 4, 5, 6, 7, 6, 5]
new = [4]
for i in range(1, len(n)):
if n[i] != 4:
new.append(n[i])
else:
break
print(new)
Upvotes: 0
Reputation: 140168
simplest logic I could figure out. Use a flag, set it if you meet the value, but first check if already set.
lst = [4, 5, 5, 6, 6, 6, 7, 6, 4, 5, 6, 7, 6, 5]
four_met = False
for e in lst:
if e == 4:
if four_met:
break
four_met = True
print(e)
Upvotes: 2
Reputation: 3790
I would try to use the index of the list.
some_list = [4, 5, 5, 6, 6, 6, 7, 6, 4, 5, 6, 7, 6, 5]
for value in range(len(some_list)):
print(some_list[value])
if some_list[value + 1] == 4:
break
Upvotes: 1
Reputation: 24691
Set a flag.
found_4 = False
for value in list:
print(value)
if value == 4:
if not found_4:
found_4 = True
else:
break
If you need to stop at, say, the third occurrence of a 4, then you can make the flag an integer instead and count up to it.
Upvotes: 0