WeirdGeek

Data Science | Machine Learning | Automation

  • Data Analytics
  • Python
  • Data Science
  • Google Apps Script
  • Machine Learning
  • Artificial Intelligence
  • SQL Server

20/11/2018 By WeirdGeek Leave a Comment

Using List and Dictionary Comprehensions in Python

List Comprehensions and Dictionary Comprehensions in Python are the important expressions you must know. Using comprehensions in the code will help us in making our code short and precise. Comprehensions in Python can achieve the output with a single line of code.

Let’s consider an example below where we used a for loop to multiply each element of a list with a two and finally printed the output as shown below.

Consider a below code with for loop:

list = [2,4,6,8,10]
new_list = []
for num in list:
    new_num = num * 2
    new_list.append(new_num)

print(new_list)
Output-
[4, 8, 12, 16, 20]

List Comprehensions in Python:

To create a list comprehensions, we have to use square brackets [] and inside square brackets, we have to define the components which are required to create list comprehension. Components of a list comprehensions are:

  • Iterable
  • Iterator variable (represent members of iterable)
  • Output Expression

Iterables are those objects which have a .iter() method associated with them. And applying iter() method to an iterable creates an iterator.Example of iterables: list(), string(), dictionaries etc.

Below is the syntax for list comprehensions in Python:
List Comprehensions in PythonTo perform the same action in list comprehensions in python, that we have done above using for loop, we can do so:

list = [2,4,6,8,10]
new_list = [num * 2 for num in list]
print(new_list)
Output-
[4, 8, 12, 16, 20]

What if we have some nested for loop and we want to achieve the same result with list comprehensions. Let’s consider an example below:

Nested for loop

 
new_list = []
for num1 in range(0,3):
        for num2 in range(4,7):
                new_num = (num1, num2)
                new_list.append(new_num)

print(new_list)
Output-
[(0, 4), (0, 5), (0, 6), (1, 4), (1, 5), (1, 6), (2, 4), (2, 5), (2, 6)]

To achieve the same result with the list comprehensions in python, we have to write a code as shown below:

new_list = [(num1, num2) for num1 in range(0,3) for num2 in range(4,7)]
print(new_list)
Output-
[(0, 4), (0, 5), (0, 6), (1, 4), (1, 5), (1, 6), (2, 4), (2, 5), (2, 6)]

 

Dictionary Comprehensions in Python:

Dictionary Comprehensions in Python are generally used to create dictionaries but this is just a single use. You can implement and use differently according to your needs. To create a Dictionary Comprehension we have to use curly brackets {} instead of square brackets [] we have used in list comprehensions.

The basic syntax for Dictionary comprehensions in Python is as below:

 Dictionary Comprehensions in Python

Let’s consider an example to create a dictionary comprehension:

Dict_Comp = {num : - num for num in range(5)}
print(Dict_Comp)
Output-
{0: 0, 1: -1, 2: -2, 3: -3, 4: -4}

Advanced Comprehensions in Python:

Advanced comprehensions can be defined as list or dictionary comprehensions expressions with conditionals on either the output expression or the iterables. Let’s see both one by one with an example to have a clear understanding.

Conditionals in comprehensions

Conditionals on iterables:

In the below code we have added conditional on the iterable. Here in the below expression, we added if statement on iterable which will check whether the number in the iterable is completely divisible by 2 and giving a remainder as 0. Output expression will provide values of those which satisfy the if condition.

[num ** 2 for num in range(10) if num % 2 == 0]
Output- [0,4,16,36,64]

Conditionals on the output expression:

Similarly, as above, this time the if statement is added on output expression and the values which satisfy the criteria otherwise the default value in else will be printed (in this case 0 is printed if the condition in if statement is false)

[num ** 2 if num % 2 == 0 else 0 for num in range(10)]
Output-
[0,0,4,0,16,0,36,0,64,0]

If you want to learn more about the basic python fundamentals which will help you in your journey to becoming data scientist or data analyst, check our posts:

  •  10 Basic Python fundamentals for Data Scientist aspirants and Data Analysis
  • 35 Pandas codes every data scientist aspirant must know

To know more about comprehensions, check out the official documentation regarding comprehensions.

Related posts:

  1. 10 Basic Python fundamentals for Data Scientist aspirants and Data Analysis
  2. 5 comparisons between generator function and generator expression in Python
  3. Creating and Computing over Dictionaries in Python
  4. 3 comparisons between List Comprehension and Generator Expression in Python

Filed Under: Python Tagged With: Dictionary Comprehensions, List Comprehensions, Python

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

Subscribe to my Blog !!

Enter your email below to subscribe my blog and get the latest post right in your inbox.

  • Home
  • Terms
  • Privacy
  • Contact Us

Copyright © 2025 · WeirdGeek · All trademarks mentioned are the property of their respective owners.