graygoo
graygoo

Reputation: 45

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.

Upvotes: 0

Views: 354

Answers (2)

David
David

Reputation: 8318

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))

Upvotes: 2

Keith
Keith

Reputation: 43044

The enumeration creates an iterator object. When you initialize a list with it (done inside the print statement), it consumes the iterator. There are no more values to return from it after that.

Upvotes: 2

Related Questions