Open In App

Comprehensions in Python

Last Updated : 18 Aug, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

Comprehensions in Python provide us with a short and concise way to construct new sequences (such as lists, sets, dictionaries, etc.) using previously defined sequences. Python supports the following 4 types of comprehension:

  • List Comprehensions
  • Dictionary Comprehensions
  • Set Comprehensions
  • Generator Comprehensions

List Comprehensions

List Comprehensions provide an elegant way to create new lists. The following is the basic structure of list comprehension:

Syntax: output_list = [output_exp for var in input_list if (var satisfies this condition)]

Note that list comprehension may or may not contain an if condition. List comprehensions can contain multiple

Example 1: Generating an Even list WITHOUT using List comprehensions

Suppose we want to create an output list that contains only the even numbers which are present in the input list. Let’s see how to do this using loops, list comprehension, and list comprehension, and decide which method suits you better.

Python3




input_list = [1, 2, 3, 4, 4, 5, 6, 7, 7]
output_list = []
   
for var in input_list:
    if var % 2 == 0:
        output_list.append(var)
   
print("Output List using for loop:", output_list)


Output:

Output List using for loop: [2, 4, 4, 6]

Example 2: Generating Even list using List comprehensions

Here we use the list comprehensions in Python. It creates a new list named list_using_comp by iterating through each element var in the input_list. Elements are included in the new list only if they satisfy the condition, which checks if the element is even. As a result, the output list will contain all even numbers.

Python3




input_list = [1, 2, 3, 4, 4, 5, 6, 7, 7]
   
list_using_comp = [var for var in input_list if var % 2 == 0]
   
print("Output List using list comprehensions:",
                               list_using_comp)


Output:

Output List using list comprehensions: [2, 4, 4, 6]

Example 1: Squaring Number WITHOUT using List comprehensions

Suppose we want to create an output list which contains squares of all the numbers from 1 to 9. Let’s see how to do this using for loops and list comprehension.

Python3




output_list = []
for var in range(1, 10):
    output_list.append(var ** 2)
       
print("Output List using for loop:", output_list)


Output:

Output List using for loop: [1, 4, 9, 16, 25, 36, 49, 64, 81]

Example 2: Squaring Number using List comprehensions

In This we use list comprehension to generate a new list. It iterates through the numbers in the range from 1 to 9 (inclusive). For each number var, it calculates the square of the number using the expression and adds the result to the new list. The printed output will contain the squares of numbers from 1 to 9.

Python3




list_using_comp = [var**2 for var in range(1, 10)]
   
print("Output List using list comprehension:",
                              list_using_comp)


Output:

Output List using list comprehension: [1, 4, 9, 16, 25, 36, 49, 64, 81]

Dictionary Comprehensions

Extending the idea of list comprehensions, we can also create a dictionary using dictionary comprehensions. The basic structure of a dictionary comprehension looks like below.

output_dict = {key:value for (key, value) in iterable if (key, value satisfy this condition)}

Example 1: Generating odd number with their cube values without using dictionary comprehension

Suppose we want to create an output dictionary which contains only the odd numbers that are present in the input list as keys and their cubes as values. Let’s see how to do this using for loops and dictionary comprehension.

Python3




input_list = [1, 2, 3, 4, 5, 6, 7]
   
output_dict = {}
   
for var in input_list:
    if var % 2 != 0:
        output_dict[var] = var**3
   
print("Output Dictionary using for loop:",output_dict )


Output:

Output Dictionary using for loop: {1: 1, 3: 27, 5: 125, 7: 343}

Example 2: Generating odd number with their cube values with using dictionary comprehension

We are using dictionary comprehension in Python. It initializes an list containing numbers from 1 to 7. It then constructs a new dictionary using dictionary comprehension. For each odd number var in the list, it calculates the cube of the number and assigns the result as the value to the key var in the dictionary.

Python3




input_list = [1,2,3,4,5,6,7]
   
dict_using_comp = {var:var ** 3 for var in input_list if var % 2 != 0}
   
print("Output Dictionary using dictionary comprehensions:",dict_using_comp)


Output:

Output Dictionary using dictionary comprehensions: {1: 1, 3: 27, 5: 125, 7: 343}

Example 1: Mapping states with their capitals without Using dictionary comprehension

Given two lists containing the names of states and their corresponding capitals, construct a dictionary which maps the states with their respective capitals. Let’s see how to do this using for loops and dictionary comprehension.

Python3




state = ['Gujarat', 'Maharashtra', 'Rajasthan']
capital = ['Gandhinagar', 'Mumbai', 'Jaipur']
   
output_dict = {}
   
for (key, value) in zip(state, capital):
    output_dict[key] = value
   
print("Output Dictionary using for loop:",output_dict)


Output:

Output Dictionary using for loop: {'Gujarat': 'Gandhinagar',
'Maharashtra': 'Mumbai',
'Rajasthan': 'Jaipur'}

Example 2: Mapping states with their capitals with using dictionary comprehension

Here we will use dictionary comprehension to initializes two lists, state and capital, containing corresponding pairs of states and their capitals. It iterates through the pairs of state and capital using the zip() function, and for each pair, it creates a key-value pair in the dictionary. The key is taken from the state list, and the value is taken from the capital list. Finally, the printed output will contain the mapping of states to their capitals.

Python3




state = ['Gujarat', 'Maharashtra', 'Rajasthan']
capital = ['Gandhinagar', 'Mumbai', 'Jaipur']
   
dict_using_comp = {key:value for (key, value) in zip(state, capital)}
   
print("Output Dictionary using dictionary comprehensions:",
                                           dict_using_comp)


Output:

Output Dictionary using dictionary comprehensions: {'Rajasthan': 'Jaipur',
'Maharashtra': 'Mumbai',
'Gujarat': 'Gandhinagar'}

Set Comprehensions

Set comprehensions are pretty similar to list comprehensions. The only difference between them is that set comprehensions use curly brackets { }

Let’s look at the following example to understand set comprehensions.

Example 1 : Checking Even number Without using set comprehension

Suppose we want to create an output set which contains only the even numbers that are present in the input list. Note that set will discard all the duplicate values. Let’s see how we can do this using for loops and set comprehension.

Python3




input_list = [1, 2, 3, 4, 4, 5, 6, 6, 6, 7, 7]
   
output_set = set()
   
for var in input_list:
    if var % 2 == 0:
        output_set.add(var)
   
print("Output Set using for loop:", output_set)


Output:

Output Set using for loop: {2, 4, 6}

Example 2: Checking Even number using set comprehension

We will use set comprehension to initializes a list with integer values. The code then creates a new set using set comprehension. It iterates through the elements of the input_list, and for each element, it checks whether it’s even. If the condition is met, the element is added to the set. The printed output which will contain unique even numbers from the list.

Python3




input_list = [1, 2, 3, 4, 4, 5, 6, 6, 6, 7, 7]
   
set_using_comp = {var for var in input_list if var % 2 == 0}
   
print("Output Set using set comprehensions:",
                              set_using_comp)


Output:

Output Set using set comprehensions: {2, 4, 6}

Generator Comprehensions

Generator Comprehensions are very similar to list comprehensions. One difference between them is that generator comprehensions use circular brackets whereas list comprehensions use square brackets. The major difference between them is that generators don’t allocate memory for the whole list. Instead, they generate each value one by one which is why they are memory efficient. Let’s look at the following example to understand generator comprehension:

Python3




input_list = [1, 2, 3, 4, 4, 5, 6, 7, 7]
   
output_gen = (var for var in input_list if var % 2 == 0)
   
print("Output values using generator comprehensions:", end = ' ')
   
for var in output_gen:
    print(var, end = ' ')


Output:

Output values using generator comprehensions: 2 4 4 6 


Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads