List Comprehension in Python – Explained with Examples

In this post we will learn about the basic of list data-type in python, creating list in python and list comprehension.


List in Python:

List is a changeable and sequenced data type which allows it to be indexed and sliced. Lists are containers used to store heterogeneous values such as integers, floats, strings, tuples, lists, and dictionaries. In python programming, lists are commonly used to store collections of homogeneous objects. A list is an iterable object meaning it can return it’s one element at a time.

There are several ways to create a new list. The simplest one is to enclose the elements in square brackets[ ].

Type conversion can also be used to create a list. Many built-in methods performs its processes and produces a list as result like String has a split method that separates a string by a character(by default white spaces) and produces a list of those separated substrings.

Creating a list by writing down all of its elements is tiresome. This process can easily be automated by using loops. If the elements of a list follow a certain sequence then it will best to use loops to create that list rather than above methods. For example, a list of first ten whole numbers.

Using loops list can be created by following three steps:

1)Create an empty list

2)Loop over an iterable or range of elements.

3)Append each element in the list

Using While loops:

The same result can be achieved using range() function.

Range() function returns an immutable sequence of numbers between a specified range. It is used when an action needs to be performed for a specific number of times.  Range() mainly takes three arguments, first one is from where the range will begin, the second one is the ending integer of the series and the last one is the difference will be between one number and the next. By default, the starting integer is 0 and the default difference is 1.

Using for loop, we can iterate over a sequence of numbers produced by the range() function. The range() function uses the generator to produce numbers within a range, i.e., it doesn’t produce all numbers at once. It generates the next value only when for loop iteration asked for it.

List Comprehension

List comprehension is a compact method used to create a list using loops. This method defines a list and its contents at the same time.  Rather than creating an empty list and appending each element, list comprehension method can be used. This method increases the speed of execution. The basic syntax of list comprehension consists of a square bracket with an expression that is executed for each element along with for loop to iterate over each element.

new_list = [ expression for element in iterable ]

It can be simplified for future remembrance, by keeping in mind that the right-hand side of comprehension looks exactly like normal for loops while the left-hand side of comprehension is the expression of loop whose result is to be stored in the list.

To make this method absolute conditional logic can be added to the comprehension. Conditionals are important because they filter out unwanted values by testing a suitable valid expression. If conditional can be added at the end of the syntax:

new_list = [ expression for element in iterable if conditional ]

If if-else is used in list comprehension then it should come before for loop in syntax:

new_list = [ expression if condition else expression for element in iterable ]

List comprehension can also be used to filter a list.

List comprehension can be used to combine several lists and create a list of lists.

Apart from list comprehension, python also provides tools like Set comprehension and Dictionary comprehension.

Set Comprehension

Sets are unique and unordered collection of data enclose in curly bracket{}. A set in python represents a mathematical notion of set. Set comprehension is just like list comprehension, just instead of list it creates sets, and instead of square bracket it has curly brackets{}.

Dictionary Comprehension

Dictionary is an unordered collection of unique_key : value pair enclose in curly bracket. Values in a dictionary can be of any datatype, mutable and can be duplicated, whereas keys can’t be repeated and are immutable. Dictionary comprehension is similar to set comprehension with an additional requirement of defining a key. In the comprehension expression key and values are separated by a colon ‘:’.

Suggested Readings –


Tags: list comprehension, creating list, creating list using loops, list type conversion, Python, python list, range function, split method, types of list, filter using list comprehension, set comprehension, dictionary comprehension, combining several lists using list comprehension, Set in python, Dictionary in python

Add Comment

%d bloggers like this: