Home > Enterprise >  For loop stop when number is reached
For loop stop when number is reached

Time:06-21

car_names = driver.find_elements_by_xpath('//h2[@]')
carnamelist = []
for cars in car_names:
    # print(len(cars))
    carnamelist.append(cars.text)
    # print((len(car_names)))

car_names are now 50, but I would like to stop when it reaches 17

How can I achieve that?

CodePudding user response:

One approach would be to zip with a range of 17 (zip stops automatically when either input is exhausted):

for cars, _ in zip(car_names, range(17)):
    carnamelist.append(cars.text)

Another would be to break in your loop:

for cars in car_names:
    carnamelist.append(cars.text)
    if len(carnamelist) >= 17:
        break

My approach would be to use zip and make it a list a comprehension:

carnamelist = [cars.text for cars, _ in zip(car_names, range(17))]

If car_names is a list (or anything else that supports slicing) you can do this much more simply with a slice:

carnamelist = [cars.text for cars in car_names[:17]]
  • Related