DataScience - Generator Functions

If we write range(10), it will return an object not the data.
For getting the data we need to add for loop as:
for i in range(10): print(i)

We can also take elements into list but it will do a lot of memory consumption if there are millions of elements.

So, we use generator functions instead.

Fibonacci number series: Next number is addition of previous 2 numbers.

Yield is a special reserved keyword that helps in generating the generator function.

Generator Function:

Note: indentation problem is here in blogging so check it by self :)

def text_fib(n): a,b = 0,1 for i in range(n): yield a a , b = b , a + b

Here, we run the for loop 'n' times. The function is generating data but not returning anything. So we call the function.
Call:

for i in text_fib(10): print(i)

O/P: 0 1 1 2 3 5 8 13 21 34

a,b = 0,1 ---> a = 0 and b = 1

range() function is by default generator function.

def text_fib1(): a,b = 0,1 while True: yield a a , b = b , a + b

fib = text_fib1()

for i in range(10): print(next(fib))

while loop works only when true, and we set it true by 'while True', so it will loop.

then we create an object, and we call it using for loop.

output: 0 1 1 2 3 5 8 13 21 34

type(fib)

o/p: generator

next() function:

we take string: s = "sudh"

for i in s: print(i)

o/p: s u d h

next(s)

o/p: TypeError: 'str' object is not an iterator

s1 = iter(s)

next(s1)

o/p: 's'

next(s1)

o/p: 'u'

next(s1)

o/p: 'd'

next(s1)

o/p: 'h'

next(s1)

o/p: StopIteration:

String is not such object where u can use next() and get data next to the pointer.

bcoz next() works only when the object is iterator.

string is iterable but not iterator.

to make it iterable, we put it in iter() function. it returns iterator which we store in s1.

when all are done, and still we put next(), it will give error 'StopIteration'.

How for loop works:
1st it counts the length, then it passes through the iter function, and does next().

It takes data, passes through the iter() function and keeps using next() function and it knows where to stop as it has length of collection.

only the iterable can be passes through iter() functions.
eg string, list,...
int is not iterable so can be passed through it.

iter(45)

o/p: TypeError: 'int' object is not iterable

iterator: where we can do use of next() function and get next element

iterable: which we can pass through iter() function for using next() on it

we make generator function by using yield keyword.

generator func: keeps on generating data one by one

iterator: we get data using next()

Did you find this article valuable?

Support Karan Thakkar by becoming a sponsor. Any amount is appreciated!