0

The code below represents one method of writing the program using list comprehension and generators.

comp = (num for num in range(2000, 3201) if num % 7 == 0 and num % 5 != 0)

print(comp)
for item in comp:
    print(item, end =", ")

This is another way of doing it, using again both list comprehension and generators, however this time, the code makes use of the * symbol inside of the print function.

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

What is the reasoning behind * being used here, given that without it, iterating over the generator would be impossible.

  • To simplify your call, `print(*(1, 2, 3))` is equivalent to `print(1, 2, 3)`. – AKX Jul 28 '20 at 12:18
  • 2
    The argument unpacking operator `*` in this case forces the evaluation of the generator expression. Remember, generators are lazy, and will not be evaluated unless they are explicitly told to do so (like via `list(...)`). The unpacked items are then passed to the `print` function as distinct arguments. – Paul M. Jul 28 '20 at 12:19
  • So what the * does, is it simply unpacks the generator expression? – Calin Paraipan Jul 28 '20 at 12:24
  • @deceze **How** did you find the "What does the star operator mean, in a function call?" duplicate? I tried *so many things* in the search box, and all I could find was the other question about parameters and a bunch of others that had been marked as duplicates of *that*. *Even knowing what it's called now*, I'm completely and utterly stumped trying to find any sequence of keywords I can put in the search box that turns that one up. And it has hundreds of upvotes! What's the deal with the question search? – Karl Knechtel Jul 28 '20 at 12:25
  • 1
    @Calin Yes, `*` unpacks *iterables*. A generator is one kind of *iterable* that can be unpacked. – deceze Jul 28 '20 at 12:26
  • Sorry guys, I'm new with Python. Where can I find the "generators" mentioned in the title? Because that changes the meaning of the question. – Nicolas Gervais Jul 28 '20 at 12:30

0 Answers0