Day 41: Introduction to Generator in Python

Generator has some connections with list comprehension. Still remember, the list comprehension is using square brackets [].

Generator expressionInstead of using square brackets, it uses normal brackets. When I execute the code, it creates generator object.

The syntax:

(output expressionforiterator variableiniterable).

What is this generator?It is same as list comprehension except it does not store the list in the memory.

List comprehensions vs generators vs dict comprehensions

So now, there are three things to remember, their differences,– List comprehension returns a list.– Dict comprehension returns a dictionary.– Generator returns generator object.

Generator is good to use when we want to generate a large volume of data, example, a range of 10*10000000. List comprehension may cause the server out of memory. However, generator will be able to do so because it has not yet generated the entire list.

List comprehensions and generator expressions look very similar in their syntax, except for the use of parentheses () in generator expressions and brackets [] in list comprehensions. Both can be iterated over.

Below is an example from DataCamp whereby, it creates generator object using bracket () and combines with next()method which I learned from the iterators to iterate each element and print the first 5 values out of the range 0 to 50. The remaining values are then print out using the for loop statement. Let see the codes below:

# Create generator object: result
result = (num for num in range(0,31))
# Print the first 5 values
print(next(result))
print(next(result))
print(next(result))
print(next(result))
print(next(result))
# Print the rest of the values
for value in result:
print(value)

Next, what we can apply in list comprehension such as conditionals in list comprehension, it applies to generator expression.

Changing the output in generator expressionsIt works similarly as the list comprehension, we are able to add to the output expression of a generator expression. Example as below: