Search code examples
pythonlist-comprehensiongenerator

Using '*" to loop through a Generator


This program works well by printing numbers from 2000 to 3200 which are divisible by 7 and not by 5 separated by a comma

print(*(i for i in range(2000, 3201) if i%7 == 0 and i%5 != 0), sep=",")

I can understand (i for i in range(2000, 3201) if i%7 == 0 and i%5 != 0) creates a generator object and i can loop it through a for loop. But this '*' symbol does the same. How to understand this?


Solution

  • The "*" is asterisk operator.
    In python, if we put an asterisk before an list/tuple or any iterable object, we can unpacking the iterable. example:

    print(*[1, 2, 3, 4], sep=", ")
    

    output:

    1, 2, 3, 4
    

    In your case, the iterable is a generator (i for i in range(2000, 3201) if i%7 == 0 and i%5 != 0)