Comprehensions in Python


We can create new sequences using a given python sequence. This is called comprehension. It basically a way of writing a concise code block to generate a sequence which can be a list, dictionary, set or a generator by using another sequence. It may involve multiple steps of conversion between different types of sequences.

List Comprehension

In this method, we create a new list by manipulating the values of an existing list. In the below example we take a list and create a new list by adding 3 to each element of the given list.

Example

given_list = [x for x in range(5)]
print(given_list)

new_list = [var+3 for var in given_list]

print(new_list)

Output

Running the above code gives us the following result −

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

Dictionary Comprehensions

Similar to the above we can take in a list and create a dictionary from it.

Example

given_list = [x for x in range(5)]
print(given_list)

#new_list = [var+3 for var in given_list]
new_dict = {var:var + 3 for var in given_list }

print(new_dict)

Output

Running the above code gives us the following result −

[0, 1, 2, 3, 4]
{0: 3, 1: 4, 2: 5, 3: 6, 4: 7}

We can also take in two lists and create a new dictionary out of it.

Example

list1 = [x for x in range(5)]
list2 = ['Mon','Tue','Wed','Thu','Fri']
print(list1)
print(list2)

new_dict ={key:value for (key, value) in zip(list1, list2)}

print(new_dict)

Output

Running the above code gives us the following result −

[0, 1, 2, 3, 4]
['Mon', 'Tue', 'Wed', 'Thu', 'Fri']
{0: 'Mon', 1: 'Tue', 2: 'Wed', 3: 'Thu', 4: 'Fri'}

Set Comprehension

We can take a similar approach as above and create new set from existing set or list. In the below example we create a new set by adding 3 to the elements of the existing set.

Example

given_set = {x for x in range(5)}
print(given_set)

new_set = {var+3 for var in given_set}

print(new_set)

Output

Running the above code gives us the following result −

{0, 1, 2, 3, 4}
{3, 4, 5, 6, 7}

Generator comprehension

New generators can be created from the existing list. These generators are memory efficient as they allocate memory as the items are generated instead of allocating it at the beginning.

Example

given_list = [x for x in range(5)]
print(given_list)

new_set = (var+3 for var in given_list)

for var1 in new_set:
   print(var1, end=" ")

Output

Running the above code gives us the following result −

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

Updated on: 17-Oct-2019

3K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements