Explanation
The code in this quiz is tricky! Here you are modifying the list that the generator wants to use.
Here is the key to understanding what is happening:
• The for loop uses the first array
• The if statement uses the second array
The reason for this oddity is that the conditional statement is late binding.
If you modify the code a bit, you can see what is happening:
Answer 33 - Deranged Generators 99
1 array = [21, 49, 15]
2 gen = ((x, print(x, array)) for x in array)
3 array = [0, 49, 88]
When you run this code, you will get the following output:
1 21 [0, 49, 88]
2 49 [0, 49, 88]
3 15 [0, 49, 88]
The output above shows you that the for loop is iterating over the original array, but the conditional
statement checks the newer array.
The only number that matches from the original array to the new array is 49, so the count is one,
which is greater than zero. That’s why the output only contains [49]!
0 Comments:
Post a Comment