Answers for "generator in python"

1

Python generator function

def gen_nums():
    n = 0
    while n < 4:
        yield n
        n += 1
Posted by: Guest on August-18-2021
1

convert generator to list python

g_to_list = list(g) # where g is a generator
Posted by: Guest on September-07-2020
2

python generator

def count_to_ten_generator():
  for number in range(10):
    yield number
my_generator = count_to_ten_generator()
first_number = next(my_generator)
list_or_the_rest = list(my_generator)
Posted by: Guest on September-19-2020
1

python generators

# Size of generators is a huge advantage compared to list
import sys

n= 80000

# List
a=[n**2 for n in range(n)]

# Generator
# Be aware of the syntax to create generators, lika a list comprehension but with round brakets
b=(n**2 for n in range(n))

print(f"List: {sys.getsizeof(a)} bitsnGenerator: {sys.getsizeof(b)} bits")
Posted by: Guest on October-08-2020
0

generators in python

def mygenerator():
    print('First item')
    yield 10

    print('Second item')
    yield 20

    print('Last item')
    yield 30
Posted by: Guest on September-20-2021

Python Answers by Framework

Browse Popular Code Answers by Language