Let’s say I have a list:

list_a = [‘a’, ‘b’,’c’, ‘d’, ‘e’, ‘f’, ‘g’]

And let’s say a function iterates through the list, say, we get to ‘e’. is it possible for the iteration to go back n (for example, back to ‘b’) steps and reiterate forward? Thanks

Why would you do that though?

i suppose you could use a while loop, whichever variable you use in the loop condition can freely be manipulated:

while i < len(list_a):
  if some condition:
    change i to desired value (decrease by n)

In some languages, you can change the iteration variable in the midst of a a for loop, but you cannot do so in Python, so you’ll need to use @stetim94’s solution and go with while. That way, you can adjust the index however you want.

I’m doing an exercise which stores data in strings in a list. Each string contains a command. The list is meant to be interpreted in order of the strings. There just so happens to be a command which tells you to repeat a number of steps based on its location in the list.

For example:

simple_assembler(['mov a 5','inc a','dec a','dec a','jnz a -1','inc a'])

in the string with ‘jnz’, the -1 tells us to move one step backwards until a = 0. So I’m trying to write a program that can repeat iteration. I tried calling the function within the function under a while statement, but I think it resets each character’s value.

Let me explain the reasoning:

in the first step ‘mov a 5’, a becomes 5
so a=5
Second step ‘inc a’, which means increase a by 1
so a = 6
third and fourth step: decrease a by one
so ‘a = 4’
fifth step ‘jnz a -1’ which means go back one step and repeat it until a = 0
last step:
a = 1

So how do we tell the program to repeat a step?

I would do it precisely as suggested by @stetim94: with a while loop:

# assuming the registers are in a dictionary, reg_dict
# given instruction_list
    i = 0    
    while not i == len(l):
        instruction = instruction_list[i]
        # break instruction into: instr = instruction, val = value, reg = register
        # code involving other instructions here
        if instr == 'jnz':
                if not reg_dict[reg] = 0:          
                    i += int(val) - 1   # value -1 since next instruction adds 1
    i += 1

1 Like