简体   繁体   中英

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?

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)

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))

You can try module % .

If the length of the list is 5 , then when i will reach 5 then i will reset to 5%5 = 0

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

Use modulo operator % to bound the size of i:

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

Or skip counting entirely if you don't need it:

my_favourite_fruits = "\n".join(["apple","orange","pear"])
while(True):
    print(my_favourite_fruits)

Set up a condition to start again.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM