Earn 20 XP

Learning Objectives

  • What are Comprehensions in Python?

  • Why Comprehensions?

  • List Comprehensions

What are Comprehensions in Python?

  • Short and concise way to construct a sequence (for example, list, set, dict, etc.) using another sequence that is already defined.
  • Don’t worry; this will be more clear when you see examples.

Why Comprehensions?

  • Comprehensions are generally faster than normal functions and for loops.


List Comprehensions

List Comprehensions - Syntax

[ 'output expression' 'for value in list' 'filtering conditions' ]

Calculate squares of numbers using list comprehension.


Select all the even numbers from the given list of numbers.


Do It Yourself

  • Using list comprehension, find the length of all the strings present in the list:
    l = [ 'abc', 'abcd', 'aabbccddd', 'eeeeeeaaaaaaa' ]
  • Try doing yourself before continuing.


Optional Video

  • Python also supports Dictionary and Set comprehensions similar to List comprehension.
  • List Comprehensions are used most often.
  • Dictionary and Set comprehensions are not commonly used.