List, Set, Dictionary Comprehensions in Python

Let’s learn about the list, dictionary, set comprehensions in python.

Photo by Kara Eads on Unsplash

Comprehensions in Python:

The comprehension consists of a single expression followed by at least one for clause and zero or more for or if clauses.

There are three comprehensions in Python.

Types of comprehensions in Python(Image Source: Author)

List Comprehensions:

List comprehensions provide a concise way to create lists. Common applications are to make new lists where each element is the result of some operations applied to each member of another sequence or iterable or to create a subsequence of those elements that satisfy a certain condition.

Syntax:

[expression for item in iterable if conditional]

The expression can be any arbitary expression, complex expressions, tuple, nested functions, or another list comprehension.

This is equivalent to

for item in iterable:
if conditional:
        expression

Return Type:

List

Using List Comprehension:

A list comprehension consists of brackets[] containing an expression followed by a for clause, then zero or more for or if clauses. The result will be a new list resulting from evaluating the expression in the context of the for and if clauses that follow it.

List Comprehension explained(Image Source: Author)

1. List comprehension vs for loop.

By using List Comprehension, it is more concise and readable comparing to for loop.

Finding square of numbers using List Comprehension vs for loop:

https://gist.github.com/IndhumathyChelliah/04a0325107e992a358031a54104a74c5

2. List comprehension vs filter.

filter:

Returns an iterator from those elements of iterable for which function returns true. iterable may be either a sequence, a container which supports iteration, or an iterator

Finding Even Numbers Using List Comprehension vs filter():

https://gist.github.com/IndhumathyChelliah/70f421f567e59523a5528495e8e6dfc5

3.List Comprehension vs map.

map:

Return an iterator that applies a function to every item of iterable, yielding the results.

Finding square of numbers using List Comprehension vs map():

https://gist.github.com/IndhumathyChelliah/5bcc494865503536a045ce2ce18cd0a6

4. Nested loops in List Comprehension.

List comprehension can contain one or more for clause.

Example 1: Flatten a list using List Comprehension with two ‘for’ clause:

https://gist.github.com/IndhumathyChelliah/363b2773afeba208a7bbc6a5dc46fcaf

5.Multiple if condition in List Comprehension.

List comprehension can contain zero or more if clause.

Example: Finding numbers that are divisible by 2 and 3.

https://gist.github.com/IndhumathyChelliah/739dbc789d81ecf25fdc9feb9d16d952

6. The expression can be tuple in List Comprehension.

We can mention expression as a tuple in a list comprehension. It should be written within parentheses. Otherwise, it will raise Error. The result will be a list of tuples.

Example 1: Creating a list of tuples using List Comprehension with two ‘for’ clause:

https://gist.github.com/IndhumathyChelliah/0790b318ce4a5926a1c77c26c11d2386

If the expression is a tuple and if not enclosed within parentheses, it will raise SyntaxError.

https://gist.github.com/IndhumathyChelliah/802be79a96873e6ce48cd0086b3688b5

Example 2:Using zip() function in List Comprehension:

https://gist.github.com/IndhumathyChelliah/c012990107a231c7dea9c21acec3014b

7. List comprehension can be used to call a method on each element.

Example 1: Calling strip() method on each element in the list. It is used to strip the white spaces.

https://gist.github.com/IndhumathyChelliah/a626abfb9fb95797d746daafe6de4f98

Example 2: Calling the upper() method on each element in the list.

https://gist.github.com/IndhumathyChelliah/c5a600e73f11b5b15b5f9d785011e062

8. List comprehension can contain complex expressions and nested functions.

Example 1:In the below example, in expression we are using the strip method and int function.

https://gist.github.com/IndhumathyChelliah/4b1f951d543c03e921e3b35e37ce1413

Example 2: In the below example, in expression, we are using abs() and str() function.

https://gist.github.com/IndhumathyChelliah/a47b97a1ad0655e92c7ce1d4733896dc

9. Nested List Comprehension.

The expression in a list comprehension can include another list comprehension also.

Example: First List comprehension given as expression will return a list of even numbers from 0 to 10. Nested list comprehension will return that expression (list of even numbers from 0 to 10) three times(range(3)).

https://gist.github.com/IndhumathyChelliah/7394b53fd281523deb0ad27e75d919e7


Set Comprehensions:

Like List comprehension, Python supports Set Comprehension also.
Set comprehension is written within curly braces{}.Returns new set based on existing iterables.

Return Type: Set

Syntax:

{expression for item in iterable if conditional}

How to find even numbers using set Comprehension:

https://gist.github.com/IndhumathyChelliah/26d9510e7e211ab0f078c91dadcab3a6

How to find the square of numbers using Set Comprehension.

https://gist.github.com/IndhumathyChelliah/ec98ca64217bd827e3a91d9e5a75fcd3

If condition in Set comprehension:

Below example, we are calculating the square of even numbers.
The expression can be a tuple, written within parentheses. 
We are using if condition to filter the even numbers.
Sets are unordered. So elements are returned in any order.

https://gist.github.com/IndhumathyChelliah/b1ad37ecf09e7db80690f1e4a13e808c


Dictionary Comprehension:

Like List and Set comprehension, Python supports Dictionary Comprehension.

A dict comprehension, in contrast, to list and set comprehensions, needs two expressions separated with a colon followed by the usual “for” and “if” clauses. When the comprehension is run, the resulting key and value elements are inserted in the new dictionary in the order they are produced.

Dictionary comprehension is written within curly braces{}.In Expression key and value are separated by :

Syntax

{key:value for (key,value) in iterable if conditional}

Return Type: dict

How to find the square of numbers using Dictionary Comprehension.

https://gist.github.com/IndhumathyChelliah/e6318cfde7610e684f07f9c02f9b2762

How to iterate through two dictionaries using dictionary comprehension:

https://gist.github.com/IndhumathyChelliah/38f3f1ebb17f45663a140d6f1cf1f7be

If Condition in Dictionary Comprehension:

Zero or more if clause can be used in dictionary comprehension.
In the below example, we are calculating the square of even numbers.

https://gist.github.com/IndhumathyChelliah/6e01f815964810e450aa318b8637e6fa

Finding the number of occurrences using dictionary comprehension:

In the below example, we are calculating the number of occurrences of each character in a string. We can call the method count() on each element in the string. count() will return the number of occurrences of a substring in the string.

We are calculating the number of occurrences of each word in the list by calling count()on each word in the list.

https://gist.github.com/IndhumathyChelliah/3bf7a2cf3a5abf0a15f9721467abdd13


Generator Expression:

A generator expression yields a new generator object. Its syntax is the same as for comprehensions, except that it is enclosed in parentheses instead of brackets or curly braces.

Generator Expression is written within ().It yields a generator. The generator is a function that returns an object (iterator) which we can iterate over (one value at a time). The performance improvement from the use of generators is the result of the lazy (on-demand) generation of values, which translates to lower memory usage.

Return Type: Generator object

https://gist.github.com/IndhumathyChelliah/bad386bbfcedca602aa4bd63aecd99c8


Conclusion:

  • Return Type
    List Comprehension-List
    Set Comprehension-Set
    Dictionary Comprehension — dict
    Generator Expression-Generator Object
  • Tuple comprehension is not supported. A generator expression is written within ().Its syntax is the same as List Comprehension. It returns a generator object.
  • List comprehension is written within []
    Set comprehension is written within {}
    Dictionary comprehension is written within {}
  • A dict comprehension, in contrast, to list and set comprehensions, needs two expressions separated with a colon.
  • The expression can also be tuple in List comprehension and Set comprehension. If an expression is tuple, it should be written within ().

Resources(Python Documentation):

List Comprehensions:

https://docs.python.org/3/tutorial/datastructures.html#list-comprehensions

Displays for lists, sets, and dictionaries:

https://docs.python.org/3/reference/expressions.html#displays-for-lists-sets-and-dictionaries

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s