1. Generator Functions in Python
# We will generate the cubes of (1-10) using a simple generator function of our own, and using a python generator which uses the Yield keyword for lazy evaluation
def cube(n):
return n**3
def simplifiedGenerator(n):
generatedResults = []
currentN = 1
while currentN <= n:
generatedResults.append(cube(currentN))
currentN += 1
return generatedResults
# This is an example of Lazy evaluation- using Python's Generators# This code does not run when called initially
# It will only return a "Generator" object
# From that object we can collect the list items, one by one
def generatorUsingYield(n):
currentN = 1
while currentN <= n:
yield cube(currentN)
currentN += 1
# Using the Simplified Generator Code, we start with numbers x = (1..10) and for each of them, we generate x^3
print "Using the Simplified Generator Code, we start with numbers x = (1..10) and for each of them, we generate x^3"
# Resulting list using simplified generator
print simplifiedGenerator(10)
# Now we use the generator code which uses yield
# After this, only the generator object will be returned
print "Result using the Generator function with Yield"
generatedValues = generatorUsingYield(10)
print "We will traverse through the values from the generator object"
# Now, we actually compute and display the values from the generator objectprint [i for i in generatedValues]
| Output from the above program:
~/work/pythontutorials$ python generators.py
Using the Simplified Generator Code, we start with numbers x = (1..10) and for each of them, we generate x^3
[1, 8, 27, 64, 125, 216, 343, 512, 729, 1000]
Result using the Generator function with Yield
We will traverse through the values from the generator object
[1, 8, 27, 64, 125, 216, 343, 512, 729, 1000]
2. List Comprehensions
# This Program demonstrates List Comprehensions in Python
# We will invoke this function to cube numbers
def cube(n):
return n**3
# Let us start by creating a list of numbers 1..10
originalList = xrange(1,11)
print "Original (Starting) list of numbers (1 to 10)"
for x in originalList:
print x
# Let us generate the cubes of 1..10 using the simple, standard for loop
print "Displaying the Cubes of 1..10 using the standard for-loop notation"
for i in xrange(1,11):
print(cube(i))
# Now let us use List Comprehensions to generate the cubes
print "Displaying the cubes by using List Comprehensions"
cubesUsingListComprehensions = [cube(x) for x in originalList]
print cubesUsingListComprehensions
|
Output from the above program:
~/work/pythontutorials$ python listComprehensions.py
Original (Starting) list of numbers (1 to 10)
1
2
3
4
5
6
7
8
9
10
Displaying the Cubes of 1..10 using the standard for-loop notation
1
8
27
64
125
216
343
512
729
1000
Displaying the cubes by using List Comprehensions
[1, 8, 27, 64, 125, 216, 343, 512, 729, 1000]
We also have some tutorials for Python for Data and Machine Learning
|
|