Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to make the items in a list run forever - python

my_favourite_fruits = ["apple","orange","pear"]
i = 0
while(True):
  print(my_favourite_fruits[i])
  i = i+1

This code currently prints the 3 list items, then crashes because there are no more list items to be printed. How do I get these to be printed over and over, using a while loop?


2 Answers

No need to count anything manually. Having a number hanging out doesn't necessarily mean anything, so handle the incoming data regardless of size and iterate with a nested loop.

my_favourite_fruits = ["apple", "orange", "pear"]

while True:
    for fruit in my_favourite_fruits:
        print(fruit)

Note that the while loop will continue forever since there is no exit condition, so that must be handled separately.

like image 84
Sam Morgan Avatar answered Oct 31 '25 05:10

Sam Morgan


itertools.cycle in Python's standard library was made just for cases like this:

from itertools import cycle    

my_favourite_fruits = ["apple", "orange", "pear"]
endless_fruits = cycle(my_favourite_fruits)
while(True):
    print(next(endless_fruits))
like image 26
das-g Avatar answered Oct 31 '25 07:10

das-g



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!