Posts

Showing posts from April 10, 2019

Unexpected behaviour with Python generator

Image
12 I was running a piece of code that unexpectedly gave a logic error at one part of the program. When investigating the section, I created a test file to test the set of statements being run and found out an unusual bug that seems very odd. I tested this simple code: array = [1, 2, 2, 4, 5] # Original array f = (x for x in array if array.count(x) == 2) # Filters original array = [5, 6, 1, 2, 9] # Updates original to something else print(list(f)) # Outputs filtered And the output was: >>> Yes, nothing. I was expecting the filter comprehension to get items in the array with a count of 2 and output this, but I didn't get that: # Expected output >>> [2, 2] When I commented out the third line to test it once again: array = [1, 2, 2, 4, 5] # Original array f = (x for x in a