Python Basic – How to Use List and Dictionary Comprehension in Python

Comprehension in Python

We will try to learn about list and dictionary comprehension in this chapter. Let us first look at an example to understand the subject of list comprehension.

Suppose numbers is a Python list containing 1–10 numbers. Now if you are asked to write a code in Python which is just another list of numbers with odd numbers and if you have no idea about list comprehension then you must write like this,

Example:

   numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
   odd_list = []
   for num in numbers:
       if num % 2 != 0:
           odd_list.append(num)
   print (odd_list)

Output:

[1, 3, 5, 7, 9]

But if you have a good idea, you can write the code in one line

Example:

   #list comprehension
   numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
   odd_list = [odd for odd in numbers if odd % 2 != 0]
   print (odd_list)

Output:

[1, 3, 5, 7, 9]

Nice, isn’t it?

That’s the fun part of Python, every language has its own unique features that set it apart. List comprehension is one such feature in the case of Python.

List Comprehension

A method of converting from one list / iterable to another.

The Python list comprehension thing is amusing, but also a little difficult for Python beginners. This section is to remove that.

Readability

It is often difficult to understand the code of list comprehension made by others. In that case, you can break it down if you want.

Example:

   numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
   odd_list = [
       odd
       for odd in numbers
       if odd % 2 != 0
   ]
   print(odd_list)


For Nested Loop

There is nothing above showing an example of a 2D matrix to show the list comprehension of a nested loop. Suppose you have a Matrix / 2D Array, and you want to flatten it, or 1D, we can solve this problem this way, you can check for the For nested loops.

By using a normal list with nested loops

Example:

   matrix_1d = []
   matrix_2d = [[1, 2, 3],
               [4, 5, 6]]
 
   for row in matrix_2d:
       for num in row:
           matrix_1d.append(num)
   print(matrix_1d)

Output:

[1, 2, 3, 4, 5, 6]

By using list comprehension of nested loops

Example:

   matrix_2d = [[1, 2, 3], [4, 5, 6]]
   matrix_1d = [num for row in matrix_2d for num in row]
   print(matrix_1d)

Output:

[1, 2, 3, 4, 5, 6]

Dictionary Comprehension

It’s like list comprehension, using a dictionary data structure instead of a list. If we want to make a dictionary from two lists, where the first is Key and the next is Value, then the general rule is to write code like this,

Example:

   role_ranking = [1, 2, 3]
   roles = ['User', 'Instructor', 'Admin']
   roles_dict = {}
 
   for i in range(len(role_ranking)):
       roles_dict[role_ranking[i]] = roles[i]
 
   print(roles_dict)

Output:

{1: 'User', 2: 'Instructor', 3: 'Admin'}

Using Dictionary Comprehension,

Example:

   role_ranking = [1, 2, 3]
   roles = ['User', 'Instructor', 'Admin']
   roles_dict = {role_ranking[i]: roles[i] for i in range(len(role_ranking))}
   print(roles_dict)

Output:

{1: 'User', 2: 'Instructor', 3: 'Admin'}

It is convenient to use list or dictionary comprehension in some cases, it is also faster than for loop in simple expressions. The performance of for loop and list comprehension in complex expressions is almost the same.

Comprehension is an important feature of Python that allows us to create lists, dictionaries, and sets in a concise and readable way. Comprehension makes it easy to create these data structures by iterating over an iterable and applying a filter or transformation to each element.

The primary advantage of comprehension is its conciseness, which leads to more readable and maintainable code. Comprehension also encourages a functional style of programming, which can make code more modular and reusable.

Comprehension is particularly useful when working with large datasets or when writing code that needs to be performant. The ability to create complex data structures in a single line of code can significantly reduce the amount of code needed to accomplish a task and make the code more efficient.

In summary, comprehension is an essential tool for any Python programmer, and mastering it can make code more concise, readable, and efficient.

Share The Tutorial With Your Friends
Twiter
Facebook
LinkedIn
Email
WhatsApp
Skype
Reddit

Check Our Ebook for This Online Course

Advanced topics are covered in this ebook with many practical examples.