简体   繁体   中英

Question regarding double loops and enumerate

Can anyone explain the internal working of this complete program, like what's happening after i reaches the last item of the list, what happens after the 3rd line of output? :)

list1 = [1,2,4,5]
for i,x in enumerate(list1):
    for y,z in enumerate(list1[i+1:],i+1):
            print(y,z)

Output:

1 2
2 4
3 5
2 4
3 5
3 5

Exit code: 0

enumerate(some_list, start=0) will return a tuple in the form of (index, list[index]) and is helpful for tracking the index of the item in some iterable that is currently being used in the loop. If you specify the start value, which you are doing in the case of the 3rd line, then the index variable will start at that value you are specifying.

For example, let's look at the first iteration.

i,x = (0,1)

In which case in the 3rd line you will be making the call enumerate(list1[0+1:], start=1) . This means that y,z will get assigned the values

y,z = (1, 2) 
# the 1 is because start=1, the 2 is because you are taking a slice 
# of the original list1 starting at index position 1 corresponding to the number 2

Not sure if that answers your question.

You can use help(enumerate) (or replace enumerate with any function) to get more info on the internal workings of the function (arguments, what it returns, and so on)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM