Here [ ] use has no effect on sum function bt shows error if not used in len function.
This is not a problem with python. What you have here is a generator that returns numbers. When used in square brackets, it first evaluates into a list (this is called list comprehension).
This works for sum because it doesn’t care whether it is a list or generator: as long as it can iterate over the object passed as an argument, then it’s happy and can calculate.
len() requires the object to be there at once. In case of list there’s a ready object, which has some length. Generators don’t have length (it’s unknown how many elements will show up).
Generators in theory can have an infinite number of elements. I wrote some example below:
import time def fibo_gen(): first = 0 second = 1 while True: yield first first, second = first + second, first for a in fibo_gen(): print(a) time.sleep(0.5)
This will print infinitely the next elements of Fibonacci sequence. But you have no idea how many of them there will be (answer: as long as the computer doesn’t blow up).