Explanation:
๐น Step 1: Create List
x = [4,3,2,1]
Current list:
[4,3,2,1]
๐น Step 2: Create Special Iterator
it = iter(x.pop, 2)
This is the 2-argument version of iter():
iter(callable, sentinel)
Meaning:
Keep calling callable()
until it returns sentinel
Here:
callable = x.pop
sentinel = 2
So Python will repeatedly do:
x.pop()
until:
x.pop() == 2
๐น Step 3: Convert Iterator to List
list(it)
Python starts calling:
x.pop()
again and again.
๐น Step 4: First Call
x.pop()
removes:
1
List becomes:
[4,3,2]
Returned value:
1
Check:
1 == 2
❌ No
Store:
[1]
๐น Step 5: Second Call
x.pop()
removes:
2
List becomes:
[4,3]
Returned value:
2
Check:
2 == 2
✅ Yes
This is the sentinel value.
Python immediately stops iteration.
⚠️ Sentinel value is not included in the result.
At this point the iterator ends.
So collected values are:
[1]
Final Output:
[1]

0 Comments:
Post a Comment