Home > Net >  update the iterator while looping through a list
update the iterator while looping through a list

Time:09-19

Newbie question... Looping through a list, and I want to update the iterator with the value at each index until I find the value '0'. Then return the index '0' is located at.

I think it's similar to a "sidewinder" algo, but I'm really unfamiliar!

here's a photo of what i'm trying to do:

here's a photo of what's i'm trying to do

CodePudding user response:

I am not quite sure what result you expect, but is this code satisfy your question?

l = [2,4,3,1,0,7,8,0,9]
i = 0

for idx, val in enumerate(l):
    idx = val
    if val == 0:
        result = l.index(val)
    print(f'index: {idx} --- value: {val}')

print(result)

CodePudding user response:

num_list  = [2,4,3,1,0,7,8,0,8]
def get_index_of_zero():
    index = 0    
    while(num_list[index] != 0):
        index = num_list[index]
    return index
print(get_index_of_zero())

This can work for you But make sure that

  1. Zero value is in the list otherwise it will run in infinity loop
  2. No element in the list should be greater than or equal to the length of the list because it will cause index error

CodePudding user response:

You need to defend against invalid values in the list and also potential recursion.

I suggest:

num_list  = [2,4,3,1,0,7,8,0,8]

def findzero(lst):
    _set = set()
    i = 0
    while True:
        if i in _set or i >= len(lst):
            break
        if lst[i] == 0:
            return i
        _set.add(i)
        i = lst[i]

print(findzero(num_list))

This function will implicitly return None if it might get into an infinite loop or if any values in the list are inappropriate

  • Related