Home > database >  Better way to rotate index back to first element in `for` loop with enumerate() in Python
Better way to rotate index back to first element in `for` loop with enumerate() in Python

Time:01-15

I hope more experienced users in Python will be able to help me make this more efficient:

If I need cyclic operations, for example if the last element of an array needs to be connected to the first element in an enumerated loop, is there a better way to do this than the following?

foo=['tic', 'tac', 'toe']
for i, v in enumerate(foo):
    if i<len(foo)-1:
        print(i, v,foo[i 1])
    else:
        print(i, v,foo[0])

This elementary method will get more complicated if more than one element rolling is required let's say to get such a result:

 0 tic tac toe
 1 tac toe tic  
 2 toe tic tac

Speaking of rolling, I looked into numpy.roll but that seems to be creating new arrays (I think?) which I am trying to avoid if possible.

Please note that this could be something such as sin(foo[i])*foo[i 1] or other complicated calculations that need a connection back to the first elements and this example from the pyhton.org website may be misleading as I am not looking for permutations.

CodePudding user response:

whenever you go circular on a linear range, I try to think of modular arithmetic

foo=['tic', 'tac', 'toe', 'baz', 'bar']

roll_factor = 2

for i in range(len(foo)):
    print(foo[(i   roll_factor) % len(foo)])

you can change roll_factor for rolling more than one element

CodePudding user response:

You can do it with slicing. This will work with any array size

foo = ['tic', 'tac', 'toe']
for i in range(len(foo)):
    print(i, ' '.join(foo[i:]   foo[:i]))

Output

0 tic tac toe
1 tac toe tic
2 toe tic tac
  • Related