+ 3
Bug? Print clearing list
The following code: nums = {1, 2, 3, 4, 5, 6} print(list(nums)) print(list(nums)) nums = {0, 1, 2, 3} & nums print(list(nums)) print(list(nums)) nums = filter(lambda x: x > 1, nums) print(list(nums)) print(list(nums)) print(len(list(nums))) gives me this result: [1, 2, 3, 4, 5, 6] [1, 2, 3, 4, 5, 6] [1, 2, 3] [1, 2, 3] [2, 3] [] 0 As you can see, all the other times I print the list it does not affect it at all, but for some reason after I apply the filter the next time the list is printed it gets cleared. Can anyone tell me why? I copied that result from LiClipse actually running Python.
2 Réponses
+ 3
This is new behavior in Python3. In Python2 you would not experience the same.
This issue is the filter method now returns an iterator instead of list so it can only be consumed once. so when you do
list(nums)
the second time you have already traversed the whole iterator and there is nothing to print
+ 1
wrethyjkl;