Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Iterate through each value of list in order, starting at random value

Given the following code:

length = 10
numbers = [x for x in range(length)]    
start_index = randint(0,length-1)
# now output each value in order from start to start-1 (or end)
# ex. if start = 3 --> output = 3,4,5,6,7,8,9,0,1,2
# ex if start = 9 ---> output = 9,0,1,2,3,4,5,6,7,8

What is the best / simplest / most pythonic / coolest way to iterate over the list and print each value sequentially, beginning at start and wrapping to start-1 or the end if the random value were 0.

Ex. start = 3 then output = 3,4,5,6,7,8,9,1,2

I can think of some ugly ways (try, except IndexError for example) but looking for something better. Thanks!

EDIT: made it clearer that start is the index value to start at

like image 345
jdf Avatar asked Jul 13 '15 17:07

jdf


People also ask

How do I iterate through a random order?

To get a list of values, use the dict. values() method and pass the resulting iterable into a list() constructor. Then use the shuffle() method of the random module upon the list of the values of the dictionary, to iterate over the items in random order.

Does for loop iterate in order?

A for loop's iteration order is controlled by whatever object it's iterating over. Iterating over an ordered collection like a list is guaranteed to iterate over elements in the list's order, but iterating over an unordered collection like a set makes almost no order guarantees.

How do you start a loop at a specific index in Python?

Python for loop index start at 1By using the slicing method [start:] we can easily perform this particular task. In this example, we have to start the index value as 1 and set 'start' to be the desired index.


1 Answers

You should use the % (modulo) operator.

length = 10
numbers = [x for x in range(length)]    
start = randint(0, length)

for i in range(length):
    n = numbers[(i + start) % length]
    print(n)
like image 64
Delgan Avatar answered Sep 25 '22 14:09

Delgan