The following list comprehension expression computes the squares of a list of numbers:
squares = [x ** 2 for x in [1, 2, 3, 4, 5]] print( squares )
can always be coded as an equivalent for loop that builds the result list manually by appending as it goes:
squares = [] for x in [1, 2, 3, 4, 5]: # This is what a list comprehension does squares.append(x ** 2) # Both run the iteration protocol internally # ww w . j a v a 2s . c om print( squares )
Both tools use the iteration protocol internally and produce the same result.