python 3 print generator

sum takes an iterable of things to add up, while print takes separate arguments to print. If you want to feed all the generator’s items to print separately, use * notation:

print(*(i for i in range(1, 101)))

You don’t actually need the generator in either case, though:

sum(range(1, 101))
print(*range(1, 101))

If you want them on separate lines, you’re expecting the behavior of multiple individual calls to print, which means you’re expecting the behavior of a regular loop:

for item in generator_or_range_or_whatever:
    print(item)

though you also have the option of specifying '\n' as an item separator:

print(*generator_or_range_or_whatever, sep='\n')

Leave a Comment