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
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.
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.
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.
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With