Python Comprehensions

Table Of Contents:

  1. What Is Comprehension?
  2. List Comprehensions
  3. Dictionary Comprehensions
  4. Set Comprehensions
  5. Generator Comprehensions

(1) What Is Comprehension?

  • Comprehension is the process of reducing the code length and being able to write it in a single statement.
  • Using comprehension you can use filtering, mapping, and apply conditional logic to the members of a sequence (such as lists, set, dictionary etc.) in a single line.
  • Comprehension allows us to filter the elements of the sequence and apply some conditional logic to an existing sequence, and it will return a new sequence.

Without Comprehensions:

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

With Comprehensions:

numbers = [1,2,3,4,5,6,7,8,9,10]

even_numbers = [i for i in numbers if i % 2 == 0]

print(even_numbers)
Output:
[2, 4, 6, 8, 10]

Note:

  • Here you can see that without comprehension it took 6 lines to complete the program.
  • With comprehension, it took 3 lines to complete the code.

(2) List Comprehension?

  • You can filter the elements of the list using list comprehensions in a single line.
  • You can able to write the for loop and conditional statements inside square brackets [ ].
  • The elements which pass the conditions will be stored inside the new list.

Syntax:

output_list = [var for var in input_list if (var satisfies this condition)]

Note:

  • The first part ‘var’ is the filtered-out value, that is going to be stored inside the new list.
  • The second part is the for loop, which is going to iterate over the existing list.
  • The third part is the conditional statement, which will check if the condition is satisfying or not.

Example-1:

vowels = ['a','e','i','o','u']
input_string = 'Abhispa'
vowels_list = [v for v in input_string if v.lower() in vowels]
print(vowels_list)
Output:
['A', 'i', 'a']

Note:

  • In this program, we have filtered out all the vowels from the input string.

Example-2:

name = 'Abhispa Pattnaik'
letters = [i for i in name]
print(letters)
Output:
['A', 'b', 'h', 'i', 's', 'p', 'a', ' ', 'P', 'a', 't', 't', 'n', 'a', 'i', 'k']

Note:

  • In this program, we are iterating over the name and storing it inside the list.

(3) Dictionary Comprehension?

  • Dictionary Comprehension works the same as List Comprehension.
  • it uses curly braces { } instead of square brackets [ ] .
  • You can filter out the dictionary elements by using this technique.

Syntax:

output_dict = {key:value for (key, value) in iterable if (key, value satisfy this condition)}

Example-1:

numbers = [2,3,4,5,6]
squares = {key:key**2 for key in numbers}
print(squares)
Output:
{2: 4, 3: 9, 4: 16, 5: 25, 6: 36}

Note:

  • In this program, we are creating a dictionary, which will contain squares of the numbers from the list.

Example-2:

names = ['Subrat','Abhispa','Arpita','Sonali','Ruchi']
marks = [59,69,79,89,99]
names_marks = {names:marks for names,marks in zip(names,marks)}
print(names_marks)
Output:
{'Subrat': 59, 'Abhispa': 69, 'Arpita': 79, 'Sonali': 89, 'Ruchi': 99}

Note:

  • In this program, we are creating a name and mark dictionary.

(4) Set Comprehension?

  • Set Comprehension works the same as Dictionary Comprehension.
  • it uses curly braces { } instead of square brackets [ ] .
  • You can filter out the set elements by using this technique.

Syntax:

output_list = {var for var in input_list if (var satisfies this condition)}

Example-1:

numbers = [1,2,1,3,4,3,5,6,5]
unique = {i for i in numbers}
print(unique)
Output:
{1, 2, 3, 4, 5, 6}

Note:

  • In this program, we will create a set from the list.
  • The set will contain unique elements only.

Example-2:

numbers = [2,2,4,4,5,6,8,8,9,10]

even_numbers = {i for i in numbers if i % 2 == 0}

print(even_numbers)
Output:
{1, 2, 3, 4, 5, 6}

Note:

  • In this program, the set will contain a unique even number of elements from the list.

(5) Generator Comprehension?

  • Generator Comprehensions are very similar to list comprehension.
  • One difference between them is that generator comprehensions use circular brackets ( ) whereas list comprehensions use square brackets [ ].
  • The major difference between them is that generators don’t allocate memory for the whole list.
  • Instead, they generate each value one by one which is why they are memory efficient.

Syntax:

output_list = (var for var in input_list if (var satisfies this condition))

Example-1:

numbers = [2,2,4,4,5,6,8,8,9,10]

even_numbers = (i for i in numbers if i % 2 == 0)

for var in even_numbers:
    print(var, end = ' ')
Output:
2 2 4 4 6 8 8 10 

Note:

  • Here even_numbers is a generator object, which we need to iterate to get the elements.

Example-2:

name = 'Subrat'

letters = (i for i in name)

for i in letters:
    print(i)
Output:
S
u
b
r
a
t

Note:

  • Here we are iterating a name and storing it inside a generator object.
  • We need to iterate over the generator object to get the individual letters.

Leave a Reply

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