• Skip to primary navigation
  • Skip to main content
  • Skip to primary sidebar
PythonForBeginners.com

PythonForBeginners.com

Learn By Example

  • Home
  • Learn Python
    • Python Tutorial
  • Categories
    • Basics
    • Lists
    • Dictionary
    • Code Snippets
    • Comments
    • Modules
    • API
    • Beautiful Soup
    • Cheatsheet
    • Games
    • Loops
  • Python Courses
    • Python 3 For Beginners
You are here: Home / Basics / Generator Comprehension in Python

Generator Comprehension in Python

Author: Aditya Raj
Last Updated: October 14, 2021

You might have used list comprehension for creating lists from different sequences and container objects. In this article, We will discuss generator comprehension to create generators in Python. We will also discuss examples of generator comprehension and how it can be used in place of list comprehension.

Table of Contents
  1. What is generator comprehension?
  2. Syntax for generator comprehension
  3. Benefits of generator comprehension
  4. Conclusion

What is generator comprehension?

Generator Comprehension is a way to initialize a generator to access elements from a container object or a sequence of data. 

Generally, We create a generator object by implementing a generator function using the yield statement. For example, suppose you want to create a generator that gives squares of elements of a given list as output. We can create such a generator using the yield statement as follows.

def num_generator():
    for i in range(1, 11):
        yield i


gen = num_generator()
print("Values obtained from generator function are:")
for element in gen:
    print(element)

Output:

Values obtained from generator function are:
1
2
3
4
5
6
7
8
9
10

Instead of implementing the generator function to create a generator, we can create a generator from any sequence in a single statement  using generator comprehension. So, let’s discuss the syntax and implementation of the generator comprehension.

Syntax for generator comprehension

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)

  • The iterable can be any iterable object such as list, set, tuple, or dictionary from which we have to create a new generator to access its elements.
  •  The element is the element of the iterable object for which we are creating the generator. 
  • The expression contains a value or any mathematical expression derived from the element.
  • The condition is the conditional expression required to exclude or include an element in the generator. The conditional statement is optional and “if condition” can be omitted if you have to access all the elements of the iterable.
  • generator is the name of a newly created generator using generator comprehension in Python. 

Let us understand this syntax using a simple program to create generators from an existing list using the generator comprehension.

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:

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)

In the above program, we have been given a list of 10 numbers and we have created a generator that gives squares of the elements of the given list as output. In the statement mygen = (element**2 for element in myList) , generator comprehension has been used to create the generator named mygen which gives as output the squares of the elements in myList. 

Let’s see an example of generator comprehension that uses a conditional statement. Suppose that you want to create a generator that gives only the squares of even numbers of the list as output. This can be implemented using generator comprehension as follows.

myList = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
print("The given list is:", myList)
mygen = (element ** 2 for element in myList if element % 2 == 0)
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:
4
16
36
64
100

In the above program, we have been given a list of 10 numbers and we have created a generator that gives squares of those elements of the given set which are even numbers as output. In the statement mygen = (element ** 2 for element in myList if element % 2 == 0), generator comprehension is used to create the generator mygen that gives squares of those elements of myList  which are even numbers as output. 

Benefits of generator comprehension

Using generator comprehension instead of generator functions to create generators in Python gives us many advantages. 

  • Generator comprehension makes us able to implement the same functionality using fewer lines of code.
  • Generator comprehension does not initialize any object unlike list comprehension or set comprehension. Thus, you can use generator comprehension instead of list comprehension or set comprehension to reduce the memory requirement of the program.
  • Generator comprehension also makes the code more readable that helps in debugging and maintenance of the source code.

Conclusion

In this article, we have discussed generator comprehension in Python. 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.

Related

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.

Enroll Now

Filed Under: Basics Author: Aditya Raj

More Python Topics

API Argv Basics Beautiful Soup Cheatsheet Code Code Snippets Command Line Comments Concatenation crawler Data Structures Data Types deque Development Dictionary Dictionary Data Structure In Python Error Handling Exceptions Filehandling Files Functions Games GUI Json Lists Loops Mechanzie Modules Modules In Python Mysql OS pip Pyspark Python Python On The Web Python Strings Queue Requests Scraping Scripts Split Strings System & OS urllib2

Primary Sidebar

Menu

  • Basics
  • Cheatsheet
  • Code Snippets
  • Development
  • Dictionary
  • Error Handling
  • Lists
  • Loops
  • Modules
  • Scripts
  • Strings
  • System & OS
  • Web

Get Our Free Guide To Learning Python

Most Popular Content

  • Reading and Writing Files in Python
  • Python Dictionary – How To Create Dictionaries In Python
  • How to use Split in Python
  • Python String Concatenation and Formatting
  • List Comprehension in Python
  • How to Use sys.argv in Python?
  • How to use comments in Python
  • Try and Except in Python

Recent Posts

  • Count Rows With Null Values in PySpark
  • PySpark OrderBy One or Multiple Columns
  • Select Rows with Null values in PySpark
  • PySpark Count Distinct Values in One or Multiple Columns
  • PySpark Filter Rows in a DataFrame by Condition

Copyright © 2012–2025 · PythonForBeginners.com

  • Home
  • Contact Us
  • Privacy Policy
  • Write For Us