Skip to content
Advertisement

Is there a pythonic way to “hot swap” a list?

Generally modifying the list you’re looping through is considered bad form, but I haven’t found a pythonic way around my issue. The crux of the problem is that I have to start the loop and perform some actions before I will know how long my list will be. I can safely assume there is a least 1 item in this list, but that’s all I know until I take the first steps.

for some additional context: I’m working with pyautogui. My script clicks a button and is then presented with multiple options, the number of options determines how many times I will need to click the button again

An example of the closest i’ve come:

x=[1] #initial 

y=[2,3,4,5] #stand in for unknown number of loops to make

for i in x:
     if i==1: #check some criteria to determine number of loops
         x.extend(y) #correct number of loops
     print(i) #do some stuff

Does anyone have any ideas on pythonic ways to “hotswap” lists like this?

Advertisement

Answer

Whenever a list iterator is asked for the next value (perhaps with next(), a for or other mechanism), it checks whether it has reached the end and should raise StopIteration. The iteration is based on the index of the list and no matter how much the list has been shuffled around, it grabs the next indexed value. That means that even if you are iterating the very last value in the list, and you add more, the iteration will continue because you have not reached an index beyond the range of the list.

In your case, that’s what you want. The for will be iterated once, but before returning to the next iteration, more values are added and those values will be iterated. And that’s what your print statement shows

1
2
3
4
5

You don’t need to know in advance how many values you will add. Whatever is in the next index position in the list continues the list.

S’all Good, Man.

User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement