I have 2 questions regarding the following 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.
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))