Changing the range of a for loop based on the length of a list for Python

3010 views python
2

If I have a list:

list = [1, 2, 3, 4, 5]

And a for loop:

for i in range(len(list)):
   if list[i] > 3:
      list.clear()
      list.append(1)
print(list)

Now, these are just examples to show the problem I'm experiencing and that is, I want to iterate through a list based on it's length. If I meet a certain condition, I want to modify the list. However, I then want the for loop to run based on the length of the new list. The main reason for this and why I included the list.clear(), is because if the list is completely different then the one defined, the condition that I'm checking for will also apply to every element within the list starting at list[0].

So basically, I want the for loop to run based on the length of a given List, then I want it to run again, based on the length of a new List, while checking each and every iteration of the first list and the second one and so on, until I want it to break.

Hopefully, I was clear enough with my question. I'm welcome to any suggestions that are reasonably simple since I'm a beginner. If there's anything I'm doing horribly wrong, please do point that out as well.

Thank you.

answered question

2 Answers

8

Why don't you write it like this:

list_range = range(len(list))
for i in list_range:
   if list[i] > 3:
      list.clear()
      list.append(1)
      list_range = range(len(list))
print(list)

Hope I understood you well.

posted this
6

It's not recommended to modify a list as you're iterating over it.

You need a way to start the for loop over from scratch, which you can do by wrapping it inside a while loop:

flag = True
while flag:
    for i in range(len(items)):
        if items[i] > 3:
            items.clear()
            items.append(1)
            # break out of the for loop and start over, because flag is still True
            break
        else if final_condition:
            # set flag to false and break out of for loop
            flag = False
            break

posted this

Have an answer?

JD

Please login first before posting an answer.