Python

## How to use List and Dict Comprehension in Python

What is List Comprehension in Python? You will learn how to make List Comprehension and show how this also works with dictionaries, called Dict Comprehension. Then show how Dict Comprehension can be used for frequency count.

In this tutorial, you will:

• Understand List Comprehension in Python: Learn the concept and syntax of List Comprehension, a concise way to create lists based on existing lists or iterables.
• Explore Dict Comprehension: Discover how List Comprehension extends to dictionaries, known as Dict Comprehension, enabling the creation of dictionaries in a similar concise manner.
• Utilize Dict Comprehension for Frequency Count: Learn how Dict Comprehension can be used to efficiently perform frequency counting on elements within a list or iterable.

By the end of the tutorial, you will have a solid understanding of List Comprehension and Dict Comprehension in Python. You will be able to leverage these powerful techniques to create lists and dictionaries more efficiently and apply them to perform frequency counting tasks effectively.

## Step 1: What is List Comprehension in Python?

List Comprehension is a syntactic construct available in some programming languages for creating a list based on existing lists.

Wikipedia.org

It is easiest to demonstrate how to create it in Python (see more about lists and about foo-loops).

```my_list = [i for i in range(10)]

print(my_list)
```

Will result in.

```[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
```

Here you use the range(10) construct, which gives a sequence from 0 to 9 that can be used in the Comprehension construct.

A more direct example is given here.

```my_new_list = [i*i for i in my_list]

print(my_new_list)
```

Which results in the following.

```[0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
```

## Step 2: List Comprehension with if statements

Let’s get straight to it (see more about if-statements).

```my_list = [i for i in range(10) if i % 2 == 0]

print(my_list)
```

This will result in.

```[0, 2, 4, 6, 8]
```

Also, you can make List Comprehension with if-else-statements.

```my_list = [i if i % 2 else -i for i in range(10)]

print(my_list)
```

This results in.

```[0, 1, -2, 3, -4, 5, -6, 7, -8, 9]
```

## Step 3: Dict Comprehension in Python

Let’s dive straight into it (see more about dict).

```my_list = [i for i in range(10)]

my_dict = {i: i*i for i in my_list}
print(my_dict)
```

Which results in.

```{0: 0, 1: 1, 2: 4, 3: 9, 4: 16, 5: 25, 6: 36, 7: 49, 8: 64, 9: 81}
```

Notice, that the lists do not need to contain integers or floats. The constructs also work with any other values.

## Step 4: Frequency Count using Dict Comprehension

This is amazing.

```text = 'aabbccccc'

freq = {c: text.count(c) for c in text}
print(freq)
```

Which results in.

```{'a': 2, 'b': 2, 'c': 5}
```

Notice, that here we will recount each instance of the letters. To avoid that you can do as follows.

```text = 'aabbccccc'

freq = {c: text.count(c) for c in set(text)}
print(freq)
```

Which results in the same output. The difference is that you only count for each letter once.

## Step 5: Want more?

I am happy you asked. Now you have learned about List and Dict Comprehension in Python.

In the next project you will Master Object-Oriented Programming by Creating a Card Game.

If this is something you like and you want to get started with Python, then this is part of an 8 hours FREE video course with full explanations, projects on each level, and guided solutions.

The course is structured with the following resources to improve your learning experience.

• 17 video lessons teaching you everything you need to know to get started with Python.
• 34 Jupyter Notebooks with lesson code and projects.
• A FREE eBook to support your Python learning.

See the full FREE course page here.

Rune

• rafael barrios (@unamedQA) says:

Dude, this is amazing. Thank you for this explanation of List Comprehension. The Video of Tower of hanoi is so cool. Thankyou Thank you Thank you.

• Rune says:

Thanks - I appreciate it.

Share
Rune

## Data Science Course Made Easy: Unlocking the Path to Success

Why Value-driven Data Science is the Key to Your Success In the world of data…

3 days ago

## 15 Machine Learning Projects: From Beginner to Pro

Harnessing the Power of Project-Based Learning and Python for Machine Learning Mastery In today's data-driven…

4 days ago

## Unlock the Power of Python: 17 Project-Based Lessons from Zero to Machine Learning

Is Python the right choice for Machine Learning? Should you learn Python for Machine Learning?…

4 days ago

## Python Mastery: Learn by Building 19 Projects

Learn Python by Creating 19 Projects Do you want to learn Python by creating projects?…

1 month ago

## Python Project: Four in Row Game (3 Core Programming Skills)

Implement a four-in-a-row game in Python On a high level, you will learn about the…

1 month ago

## Python Project: Valid Parentheses (6 Essential Skills)

Implement a valid parentheses checker in Python Keep your skills sharp and start learning Python…

1 month ago