ubant
ubant

Reputation: 39

How to reset for loop to make it read a list from the beginning

So I have a for loop, which deletes elements of the list if it meets some conditions. When it deletes the 2nd element, it continues for loop from 2nd element my problem is that I want it to start this loop from the beginning, so it checks a list from 1st item. Is it possible?

some_list = ["one", "two", "two", "one", "two", "three", "two"]

for element in some_list:
    if element == "one":
        if some_list.index(element) + 1 == two:
            some_list.remove(some_list.index(element) + 1)

here's some sample code. I want it to check there's "one", remove "two" and when it removes, start again at "one" in the beginning, remove "two", go to "one again, go to 2nd "one", remove "two" and list looks like this:

some_list = ["one", "one", "three", "two"]

Upvotes: 1

Views: 1099

Answers (4)

Jacob Lee
Jacob Lee

Reputation: 4690

Your method is somewhat inefficient, as all the elements “two” are removed by the end of the loop, so it would be better to straight out remove all “two” elements.

for i, elem in enumerate(some_list):
    if elem == “two”:
        del some_list[i]

For the sake of answering the question, though, here is my solution:

i=0
while i != len(some_list):
    if some_list[i] == “one” and some_list[i+1] == “two”:
        del some_list[i+1]
    else:
         i += 1

Upvotes: 1

ibutskhrikidze
ibutskhrikidze

Reputation: 156

You can try while loop instead of for loop and what you need will be this:

some_list = ["one", "two", "two", "one", "two"]

i = 0
while i < len(some_list):
    element = some_list[i]
    if element == "one":
        idx = i + 1
        if idx < len(some_list) and some_list[idx] == "two":
            some_list.pop(idx)
            i -= 1
    i += 1

print(some_list)

Upvotes: 2

Mohammad Anas
Mohammad Anas

Reputation: 52

I would suggest using a while loop since the for loop in python once initiated follows along the initial execution unlike C++, Java, etc

some_list = ["one", "two", "two", "one", "two"]
i = 0
while( i != (len(some_list) - 1)):
    if some_list[i] == "one":
        if some_list[i + 1] == 'two':
            del some_list[i + 1]
            i = 0
            continue
    i = i + 1
print(some_list)

Upvotes: 3

Sabareesh
Sabareesh

Reputation: 751

Algorithm to delete all 'two''s that occur after 'one':

>>> def del_two(some_list):
...     i = 0
...     while i < len(some_list):
...             if some_list[i] != 'one':
...                     i += 1
...                     continue
...             i += 1
...             while i < len(some_list) and some_list[i] == 'two':
...                     del some_list[i]

>>> some_list = ["one", "two", "two", "one", "two"]
>>> del_two(some_list)
>>> print(some_list)
['one', 'one']

Upvotes: 2

Related Questions