Home > Net >  How to avoid using range(len) but having the same result
How to avoid using range(len) but having the same result

Time:10-15

The question maybe too stupid, but I wanna ask anyway.

Currently, I use range(len) to run for loop, the result will like this (Loop 4 times):

Range w/ Len

range(0, 4)
['a', 'b', 'c', 'd']
range(0, 3)
['b', 'c', 'd']
range(0, 2)
['c', 'd']
range(0, 1)
['d']

But I cannot have the same result using enumerate, the result would be like this if just replacing range(len) with enumerate (Loop once only):

Enumerate

0 a
['a', 'b', 'c', 'd']
1 c
['b', 'c', 'd']

I know I did something wrong using enumerate, but may I know how to use enumerate or similar method but with the same result of range(len)?

My Code :

#random_stuff
aList1 = ["a","b","c","d"]

aList2 = ["a","b","c","d"]

def do_random_stuff_1():
    print(aList1)
    return

def do_random_stuff_2():
    print(aList2)
    return

def enumerate_list():
     for idx, x in enumerate(aList1):

        print(idx, x)
        aList4One1 = aList1[0]
        do_random_stuff_1()
        aList1.pop(0)
        aList4One1 = None

        if idx >= 0:
            continue
        else:
            return

def range_len_list():
    for x in range((len(aList2))):
        
        print(range((len(aList2))))
        aList4One2 = aList2[0]
        do_random_stuff_2()
        aList2.pop(0)
        aList4One2 = None

        if len(aList2) >= 1:
            continue
        else:
            return

if __name__ == "__main__":
    print("Enumerate")
    enumerate_list()
    print("\n")
    print("Range w/ Len")
    range_len_list()

CodePudding user response:

IIUC you could implement enumerate_list like this:

def enumerate_list(lst):
  idx = 0
  while lst:
    value = lst.pop(0)
    print(idx, value)
    do_something(value)
    idx  = 1

So no enumerate or range involved.

Note that this is destructive

CodePudding user response:

You shouldn't modify the list that you're enumerating over. Make a copy of the list and enumerate over that.

There's no need for

        if idx >= 0:
            continue
        else:
            return

since idx is always at least 0.

So rewrite it as:

def enumerate_list():
     for idx, x in enumerate(aList1.copy()):

        print(idx, x)
        aList4One1 = aList1[0]
        do_random_stuff_1()
        aList1.pop(0)
        aList4One1 = None
  • Related