Iterate through each list value in order, starting with a 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 / easiest / most pythonic / coolest way to iterate over the list and print each value every time, starting from the beginning and packing to start-1 or end if the random value is 0.

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

I can come up with some ugly ways (try, with the exception of IndexError, for example), but we are looking for something better. Thanks!

EDIT: clarified that the beginning is an index value starting with

+5
source share
4 answers
 >>> start = randint(0, len(numbers)) >>> start 1 

You can use list slicing and then iterate over this

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

You can also use the % module operator in list comprehension

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

You must 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) 
+5
source

What is the best / easiest / most pythonic / coolest way ...

You can use collections.deque and rotate like this

 >>> from collections import deque >>> d = deque(numbers) >>> d.rotate(-9) >>> d deque([9, 0, 1, 2, 3, 4, 5, 6, 7, 8]) >>> >>> d = deque(numbers) >>> d.rotate(-2) >>> d deque([2, 3, 4, 5, 6, 7, 8, 9, 0, 1]) 
+3
source

You can try iterating through the list with simple conditional loops.

 i = start while(True): print i, if i==numbers[-1]: # If it the last number i=numbers[0] else: i += 1 if i==start: # One iteration is over break 

Opens 3 4 5 6 7 8 9 0 1 2

0
source

All Articles