Rezha Julio

Hi!
My name is Rezha Julio
I am a chemist graduate from Bandung Institute of Technology. Currently working as Data Engineer at Traveloka.
You can reach me by email:

contact@rezhajulio.id

, @ Q Q

Powered by Hugo

filter by tags

Python GeneratorNext, Function or Method ?

time to read 1 min | 74 words

While in Python 2 it was possible to use both the function next() and the .next() method to iterate over the resulting values of a generator, the later has been removed with the introduction of Python 3.

Consider the sample generator:

def sample_generator():
    yield "a"
    yield "b"
    yield "c"

In Python 2:

a = sample_generator()
print(next(a)) # prints 'a'
print(a.next()) # prints 'b'

But in Python 3:

print(next(a)) # prints 'a'
print(a.next()) # AttributeError

Python GeneratorGenerator Expressions

time to read 1 min | 198 words

Generator expressions are a high performance and memory efficient generalization of list comprehensions and generators. Imagine we want to sum up all even number ranging from 1 to 100.

Using list comprehension:

even_sum = sum([x for x in range(1, 100)
               if x % 2 == 0])
print(even_sum)
#2450

This will prove inefficient in the case of a large range because it first creates a list, it iterates over it and then returns the sum. The same result can be achieved with a generator expression:

even_sum = sum(x for x in range(1, 100)
               if x % 2 == 0)
print(even_sum)
#2450

The generator expressions syntax says that it must be enclosed inside parenthesis (). A generator for squares of numbers:

squares = (x * x for x in range(1,10))

This generator can now be converted to a list with:

print(list(squares))
# [1, 4, 9, 16, 25, 36, 49, 64, 81]

Or, iterate over it with a for loop:

for item in squares: print(item)

This’ll print nothing, since a generator can only be iterated over once. To access values from a generator more than once, either save the values in a list, or define and then run the generator again.

Python GeneratorYield Keyword

time to read 1 min | 158 words

The yield keyword is fundamental to the creation of generators. Consider the following generator function:

def createGenerator():
    print('Initial call')
    yield '1'
    print('Second call')
    yield '2'

a = createGenerator()

Calling the createGenerator() function will create a generator object stored as a. Note that the code inside the generator function will not be run yet.

print(next(a)) 
# Initial call
# 1

The first time the generator object is iterated over (in a loop or with next()), the function code will be run from the start until the first yield. The value in the yield statement is returned and the current position in the code is saved internally.

print(next(a))
# Second call
# 2

The second next call will resume the code from just after the previous yield and will continue running it until another yield is found where it returns the desired value.

When there are no more yield keywords, the generator object is considered empty.

print(next(a)) # StopIteration error

Python GeneratorWhat are Generators?

time to read 1 min | 166 words

Generators are special functions that implement or generate iterators. Generators are functions which behave like iterators, but can have better performance characteristics. These include:

  • Creating values on demand, resulting in lower memory consumption.
  • The values returned are lazily generated. Hence, it is not necessary to wait until all the values in a list are generated before using them.

However, the set of generated values can only be used once.

Generators look like normal functions, but instead of the return statement they make use of the yield statement.cThe yield statement tells the interpreter to store local variables and record the current position in the generator, so when another call is made to the generator, it will resume from that saved location and with the previous values of local variables intact.

Consider this generator:

def test_generator():
    yield 1
    yield 2
    yield 3

g = test_generator()

We can now iterate over g using the next() function:

print(next(g)) # 1
print(next(g)) # 2
print(next(g)) # 3
print(next(g)) # StopIteration error

RECENT SERIES

  1. java 101 (13):
    Apr 29, 2017 - Translating Scanner tokens into primitive types
  2. python data structure (5):
    May 03, 2017 - Enhance your tuples
  3. python function (2):
    Apr 16, 2017 - Lambda Functions in Python
  4. python generator (4):
    Apr 26, 2017 - Next, Function or Method ?

Friends of Rezha