pub-3785248829033902 | Python: Generator | - Big data with Python

| Python: Generator |

AGenerator is effectively a function that returns (data) before it is finished, but it pauses at that point, and you can resume the function at that point.


Generator simplifies creation of iterators - please refer to Iterators for better understanding! A generator is a function that produces a sequence of results instead of a single value.

The (or one) benefit of generators is that because they deal with data one piece at a time, you can deal with large amounts of data; with lists, excessive memory requirements could become a problem.

Generators, just like lists, are iterable, so they can be used in the same ways. There are different ways to create a generator. You can use the parentheses syntax or you can use yield. Another interesting feature is that generators can be "infinite" -- iterators that don't stop.

The best way to learn new things is to take a practical approach of the things you want to learn. Here is a fragment of code that demonstrates the use of the generator statement in Python:

Æ’ python command

def num(x):
  for i in range(x):
    if i % 2 == 0:
      yield i

print(list(num(9)))

output

[0, 2, 4, 6, 8]   


Previous
Next Post »