Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In Python, when iterating through items in list, how to start at 0 if end is reached?

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?

like image 381
phimath Avatar asked Nov 20 '25 09:11

phimath


1 Answers

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
like image 138
David K. Hess Avatar answered Nov 21 '25 23:11

David K. Hess



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!