Reputation: 131
I am attempting to use a for loop to iterate through a list of items. I do not need all items in the list and would like to end on a certain index position. How would I go about this in python?
I've attempted to use enumerate and alter my code to other options. After hours of searching I am having a hard time understanding how to end a loop upon a certain parameter in python. The code I am providing WORKS excellent for my interests. I would only like to stop the for loop upon a certain index.
train_times = driver.find_element_by_class_name('stop-times').text
str(train_times)
train_times=train_times.split('\n')
print("Schedule for 900 East Station:")
for i in train_times:
print('There is a train at {}'.format(i))
print('--------------------------------------')
Upvotes: 1
Views: 5283
Reputation: 71
You can use break
for loops:
train_times = driver.find_element_by_class_name('stop-times').text
str(train_times)
train_times=train_times.split('\n')
print("Schedule for 900 East Station:")
for i, train in enumerate(train_times):
if i == 400:
break
print('There is a train at {}'.format(train))
print('--------------------------------------')
See more about break on loops: https://docs.python.org/3.7/tutorial/controlflow.html#break-and-continue-statements-and-else-clauses-on-loops
Upvotes: 2
Reputation: 33
You can use break and enumarate.
for index, value in enumerate(train_times):
if index == x : break
// your code here
Upvotes: 2
Reputation: 1876
As you know the exact index to stop in the string you can provide the index to loop from and to
for i in train_times[:20]:
print('There is a train at {}'.format(i))
print('--------------------------------------')
Upvotes: 3