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


given following code:

length = 10 numbers = [x x in range(length)]     start_index = randint(0,length-1) # output each value in order start 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 best / simplest / pythonic / coolest way iterate on list , print each value sequentially, beginning @ start , wrapping start-1 or end if random value 0.

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

i can think of ugly ways (try, except indexerror example) looking better. thanks!

edit: made clearer start index value start at

>>> start = randint(0, len(numbers)) >>> start 1 

you can use list slicing iterate on that

>>> numbers[start:] + numbers[:start] [1, 2, 3, 4, 5, 6, 7, 8, 9, 0] 

you can use modulus % operator in list comprehension

>>> [numbers[i%len(numbers)] in range(start, start + len(numbers))] [1, 2, 3, 4, 5, 6, 7, 8, 9, 0] 

Comments

Popular posts from this blog

searchKeyword not working in AngularJS filter -

sequelize.js - Sequelize: sort by enum cases -

user interface - how to replace an ongoing process of image capture from another process call over the same ImageLabel in python's GUI TKinter -