02: Python comprehensions tutorial

Q. What is a comprehension?
A. Comprehensions are constructs that allow sequences to be built from other sequences. Python 2.0 introduced list comprehensions and Python 3.0 comes with dictionary, set and generator comprehensions.

List Comprehension

Set Comprehension

Given a list return a set.

Dictionary Comprehension

Given a list return a dict.

Generator Comprehension

A generator expression is like a list comprehension, but instead of finding all the items you’re interested and packing them into list, it waits, and yields each item out of the expression, one by one.

Nested list comprehension

How to flatten a list of lists using a nested list comprehension?

What if you want to flatten lists with more than two elements?

Use comprehension instead of map or filter

Using map or filter function as shown below is an anti-pattern.

Anti-pattern
Best Practice
Anti-pattern
Best Practice

Coding examples

Example #1: Can you write code to remove vowels from a give sentence?

Example #2: Take two list of same length as input and return a dictionary with one as keys and other as values.

Example #3: Can you refactor the following code smell?

Solution is with list comprehension:

It is important to note that the list comprehension also has a performance boost.


Java & Big Data Interview FAQs

Java Key Areas Interview Q&As

800+ Java Interview Q&As

Java & Big Data Tutorials