Show the difference between a Python list comprehension and a generator expression.
The syntax is almost the same in both cases. The only visible difference is that a list comprehension uses square brackets and a generator expression uses round ones, but the object that you get back is completely different.
squares_list = [n * n for n in range(5)]
squares_gen = (n * n for n in range(5))
print(type(squares_list).__name__)
print(type(squares_gen).__name__)
print(squares_list)
print(list(squares_gen))
# The generator is now exhausted.
print(list(squares_gen))
The list comprehension works out all five values straight away and stores them. The generator expression creates a generator object that holds nothing except the range and a position, and it works out each square only when that value is asked for. The call to list() then drains the generator and produces the same five values.
The last line shows the second important difference. A generator is single-use, so once it has been drained, listing it again gives you an empty list. A list comprehension, on the other hand, can be traversed as many times as you like.
There is a third difference as well. A generator cannot be indexed, it has no length, and it cannot be sorted or reversed. Any of those operations would have to consume the whole generator, and once it is consumed there is nothing left to work with.
There is one syntax rule to remember. A generator expression must always be surrounded by brackets when it is the only argument of a function, because the brackets of the function call would otherwise be ambiguous. That is why you see sum(n * n for n in range(5)) with the inner round brackets, and why list(...) uses square brackets to make the outer grouping clear.