I am iterating through a list in Python.
mylist = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k']
i = 0
while i <= 27:
print mylist[i]
i +=1
I am looking for a simple / elegant solutition so that when i is 11, it grabs 'a' from mylist. I'd rather not use a complex set of if statments to check if the end of the list is reached. Also, I would rather not make a new list with mylist duplicated numerous times, as these lists are rather long.
Is there a simple way to do this?
Try modulo math:
mylist = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k']
i = 0
while i <= 27:
print mylist[i % len(mylist)]
i +=1
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With