Generators in Python are a very useful tool for accessing elements from a container object. In this article, we will discuss how we can create a generator from a list and why we need to do this. Here we will use two approaches for creating the generator from a list. First using the generator functions and the second using generator comprehension.
Convert a list to generator using generator function
Generator functions are those functions that have yield statements instead of return statements. Generator functions have a specialty that they pause their execution once the yield statement is executed. To resume the execution of the generator function, we just need to use the next() function with the generator to which the generator function has been assigned as the input argument.
For example, suppose that we want the squares of the elements of a given list. One way to obtain the squares of the elements may be the use of list comprehension or a function to create a new list having squares of elements of the existing list as follows.
def square(input_list):
square_list = []
for i in input_list:
square_list.append(i ** 2)
return square_list
myList = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
print("The given list is:", myList)
squares = square(myList)
print("Elements obtained from the square function are:")
for ele in squares:
print(ele)
Output:
The given list is: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
Elements obtained from the square function are:
1
4
9
16
25
36
49
64
81
100
We can also create a generator instead of a new list to obtain squares of the elements of the existing list using generator function.
To create a generator from a list using the generator function , we will define a generator function that takes a list as input. Inside the function, we will use a for loop in which the yield statement will be used to give the squares of the elements of the existing list as output. We can perform this operation as follows.
def square(input_list):
square_list = []
for element in input_list:
yield element ** 2
myList = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
print("The given list is:", myList)
squares = square(myList)
print("Elements obtained from the square generator are:")
for ele in squares:
print(ele)
Output:
The given list is: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
Elements obtained from the square generator are:
1
4
9
16
25
36
49
64
81
100
Convert a list to generator using generator comprehension
Instead of using a generator function, we can use generator comprehension to create a generator from a list.The syntax for generator comprehension is almost identical to list comprehension.
The syntax for set comprehension is: generator= (expression for element in iterable if condition)
You can create a generator from a list using the generator comprehension as follows. Here, we have used the implemented the same example given in the previous section.
myList = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
print("The given list is:", myList)
mygen = (element ** 2 for element in myList)
print("Elements obtained from the generator are:")
for ele in mygen:
print(ele)
Output:
The given list is: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
Elements obtained from the generator are:
1
4
9
16
25
36
49
64
81
100
Why create a generator from a list?
Generators can be used in place of a list for two reasons. Let us understand both of them one by one.
- When we create a new list from an existing list, the program uses memory for storing the elements of the existing list. On the other hand, a generator uses a minimal amount of memory that is almost similar to the memory required by a function. Hence, Using generators in place of a list can be more efficient if we just have to access the elements from the newly created list.
- With generators, we can access the next element of the list at random occasions without explicitly using any counter. For this, we can use the next() method to extract the next element from the generator.
For example, Consider a situation in which we have a list of 100 elements. We continually ask the user to input a number and whenever they enter an even number, we print the next element of the list.
Here, the user input does not have any pattern. Due to this, we cannot access the elements of the list using a for loop. Instead, we will use a generator to print the next element from the list using the next() function as shown in the following example.
myList = range(0, 101)
myGen = (element ** 2 for element in myList)
while True:
user_input = int(input("Input an even number to get an output, 0 to exit:"))
if user_input == 0:
print("Good Bye")
break
elif user_input % 2 == 0:
print("Very good. Here is an output for you.")
print(next(myGen))
else:
print("Input an even number.")
continue
Output:
Input an even number to get an output, 0 to exit:23
Input an even number.
Input an even number to get an output, 0 to exit:123
Input an even number.
Input an even number to get an output, 0 to exit:12
Very good. Here is an output for you.
0
Input an even number to get an output, 0 to exit:34
Very good. Here is an output for you.
1
Input an even number to get an output, 0 to exit:35
Input an even number.
Input an even number to get an output, 0 to exit:0
Good Bye
Conclusion
In this article, we have discussed two ways to create a generator from a list. To learn more about python programming, you can read this article on list comprehension. You may also like this article on the linked list in Python.
Recommended Python Training
Course: Python 3 For Beginners
Over 15 hours of video content with guided instruction for beginners. Learn how to create real world applications and master the basics.