Completely loop over a list with a different start index
So I have this list
station_list = [1, 2, 3, 4]
This is an example, the real list may be longer, but always this pattern with increasing integers. As part of my code, if any condition is met, I want to access that list at a different point than 1. Let's say I want to start iterating at 2. How can I iterate over a list using for-loop
starting at 2, but still getting all elements exactly once? Therefore, the iteration order must be 2, 3, 4, 1
.
source to share
You can do it:
station_list = [1, 2, 3, 4]
start = 1 # item = 2 is at index position 1!
for item in (station_list[start:] + station_list[:start]):
# your code here
these outputs:
[2, 3, 4, 1]
You can read more about slicing in python here
And if you want more information about lists in Python, this might help.
source to share
Easy way: create a reordered list using two snippets from the original list:
station_list = [1, 2, 3, 4]
start = 1
for i in station_list[start:] + station_list[:start]:
print (i)
If you don't want to create a list of reordered stations, you can use index wrapping:
station_list = [1, 2, 3, 4] start = 1 n = len(station_list) for i in range(n): print (station_list[(i+start)%n])
source to share
First, define the visible list where it is # !
. (That is, after defining the list.)
int_list = [1, 2, 3, 4, 5, 6]
seen = [] # {1}
Then define the beginning.
start = 2
This is part of the cycle.
for n in range(start, list_length): # starts at position you desire...
print(int_list[n])
seen.append(int_list[n])
If you start at a position not equivalent to the start, this goes back again ...
if int_list != seen: # if there are still some ints at start, go redo the loop until a seen int is found
for x in range(0, list_length):
print(int_list[x])
seen.append(int_list[x])
if int_list[x+1] in seen:
break
All code:
int_list = [1, 2, 3, 4, 5, 6]
seen = []
start = 2
list_length = len(int_list)
for n in range(start, list_length): # starts at position you desire...
print(int_list[n])
seen.append(int_list[n])
if int_list != seen:
# if there are still some ints at start, go redo the
#loop until a seen int is found
for x in range(0, list_length):
print(int_list[x])
seen.append(int_list[x])
if int_list[x+1] in seen:
break
Not that compact, but it works.
source to share