Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Loop Through List and Restart at Beginning

Tags:

python

I have a list and I want to be able to return each item in sequence and when it reaches the last item (a7) continue running from the beginning. An added complexity is that the script will not run continuously (it is manually stopped and started) so it will need to store the previously called item in some way so that it works the next time the script is run.

Here's an extract of the list:

part_list = ['a1', 'a2', 'a3', 'a4', 'a5', 'a6', 'a7']

The basic logic of the script is:

if var_one == var_two:
    [return next item from part_list]

So, on the first run it should return a1, the second time it runs it should return a2, the third time, a3, etc.

like image 661
James Avatar asked Dec 30 '25 17:12

James


2 Answers

Use itertools.cycle:

from itertools import cycle
part_cycle = cycle(['a1', 'a2', 'a3', 'a4', 'a5', 'a6', 'a7'])

# below code is part of a function
if var_one == var_two:
    return next(part_cycle)

alternative to save the state out of the interpreter

n = 4 ## counter to save (could use a file, database, pickle, etc.)
      ## ensure that the type is int

part_list = ['a1', 'a2', 'a3', 'a4', 'a5', 'a6', 'a7']

# below code is part of a function
if var_one == var_two:
    n += 1
    return part_list[n%len(part_list)]
full demo
# read the saved counter, or initialize
try:
    with open('state.txt', 'r') as f:
        idx = int(f.read().strip())
        print(idx)
except FileNotFoundError:
    idx = -1

part_list = ['a1', 'a2', 'a3', 'a4', 'a5', 'a6', 'a7']    

# this is the part where the computation is done
# replace it with your function
# the critical steps are:
#   1- to increase the counter
#   2- to slice using the modulo (part_list[idx%len(part_list)])
for i in range(10):
    idx += 1
    print(part_list[idx%len(part_list)])

# save the counter
with open('state.txt', 'w') as f:
    f.write(f'{idx}')
like image 71
mozway Avatar answered Jan 02 '26 05:01

mozway


Here is a simple prototype code for returning next item on each run and keeps track of the last returned item for the next run.

Prerequisite: create a simple text file - 'return_stat.txt' with the last item written in it (here the last item is a7).

part_list = ['a1', 'a2', 'a3', 'a4', 'a5', 'a6', 'a7']

def return_next(current_item):
    idx = part_list.index(current_item)
    if idx<(len(part_list)-1):
        return part_list[idx+1]
    else:
        return part_list[0]

with open('return_stat.txt') as f:
    current_item = f.readlines()[0]

next_item = return_next(current_item)       
print(next_item)

with open('return_stat.txt', 'w') as f:
    f.write(next_item) 
like image 45
aprath Avatar answered Jan 02 '26 05:01

aprath



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!