python generators

Solutions on MaxInterview for python generators by the best coders in the world

showing results for - "python generators"
Emanuela
09 May 2019
1def gen_nums():
2    n = 0
3    while n < 4:
4        yield n
5        n += 1
6
Magdalene
04 Apr 2017
1# Size of generators is a huge advantage compared to list
2import sys
3
4n= 80000
5
6# List
7a=[n**2 for n in range(n)]
8
9# Generator
10# Be aware of the syntax to create generators, lika a list comprehension but with round brakets
11b=(n**2 for n in range(n))
12
13print(f"List: {sys.getsizeof(a)} bits\nGenerator: {sys.getsizeof(b)} bits")
Miranda
06 Jan 2021
1def mygenerator():
2    print('First item')
3    yield 10
4
5    print('Second item')
6    yield 20
7
8    print('Last item')
9    yield 30
10