🐍 Example 1: Create a generator that generates the squares of numbers up to some number N
def gensquares(N):
for x in range(N):
yield x**2
a = gensquares(10)
next(a)
Example 2: Create a generator that yields "n" random numbers between a low and high number (that are inputs)
import random
def rand_num(low,high,n):
for x in range(n):
yield random.randint(low,high)
y = rand_num(1,10,12)
next(y)
Example 3: Use the iter() function to convert the string below into an iterator
s = 'hello'
p = iter(s)
next(p)
Example 4: Example for Generator Comprehension
my_list = [1,2,3,4,5]
#The below line is a shortcut to create a generator
gencomp = (item for item in my_list if item > 3)
next(gencomp)
Comments
Post a Comment