List Comprehension in Python

Creating new lists from other iterables

Rupesh Mishra
May 11, 2017 · 2 min read

List comprehensions are used for creating new lists from other iterables.

As list comprehensions returns lists, they consist of brackets containing the expression, which is executed for each element along with the for loop to iterate over each element.

This is the basic syntax:

new_list = [expression for_loop_one_or_more conditions]

For example, find the squares of a number using the for loop:

Finding squares using list comprehensions:

Here, square brackets signifies that the output is a list. n**2 is the expression executed for each element and for n in numbers is used to iterate over each element. In other words, execute n**2 (expression) for each element in numbers.

A more complex example of list comprehension:

Find common numbers from two lists using for loop.

Using conditions in list comprehensions:

Find common numbers from two list using list comprehension:

Return numbers from the list which are not equal as a tuple:

Here. as we are returning a list of tuples, tuples must be in parenthesis to avoid errors. In the above example, tuples with a and b will be printed such that a and b are not the same.

List comprehensions can also be used to iterate over strings, as shown below:

This example converts each of the string from list_a to a smaller case.

Like tuples, list comprehensions can be used to produce a list of a list, as shown below:

Here we use list_a to create square_cube_list, which is a list of list in Python containing squares and cubes of the numbers from list_a


Rupesh Mishra

Written by

Full Stack Developer | Freelance Blogger

Better Programming

Advice for programmers.

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade