Search code examples
pythonfor-loopenumerate

Python enumerate and for loops output


I have 2 questions regarding the following code:

  1. Why do I lose (0, 1) from enum_l1 and (0, 3) from enum_l2 after the for loops?
  2. If I do not put the first 2 prints as comments, I will not see the last 2 prints (in short, the program will only display "enum_l1 before:" and "enum_l2 before:" without "enum_l1 after:" and "enum_l2 after:"). The opposite is also true. Why? Why does I need to add to see all 4 prints in this code?
list1 = [1,2,3]
list2 = [3,1,2]

enum_l1 = enumerate(list1)
#print("enum_l1 before: ", list(enum_l1))
enum_l2 = enumerate(list2)
#print("enum_l2 before: ", list(enum_l2))

for count1, value1 in enum_l1:
    for count2, value2 in enum_l2:
        print("enum_l1 after: ", list(enum_l1))
        print("enum_l2 after: ", list(enum_l2))

Output:

enum_l1 before:  [(0, 1), (1, 2), (2, 3)]
enum_l2 before:  [(0, 3), (1, 1), (2, 2)]

enum_l1 after:  [(1, 2), (2, 3)]
enum_l2 after:  [(1, 1), (2, 2)]

Thank you.


Solution

  • enum_l1 is an iterator. Inside the loop you extract the first element which is (0,1) and then instead of printing count1, value1 you print the state of the iterator enum_l1 which misses the first instance.

    The behavior you are seeing inside the loop is equivalent to:

    enum_l1 = enumerate(list1)
    print(next(enum_l1))
    print(list(enum_l1))