List Comprehension in Python

Abhilash Jose
Abhilash Jose  - Data Science Specialist
3 Min Read

List comprehension is a concise way to create lists in Python. It provides an elegant way of generating lists by applying an expression to each item in an iterable (like a list or range) without the need for a traditional for loop or append() method. It makes the code cleaner, more readable, and often more efficient.

Basic Syntax

The basic structure of list comprehension is:

This syntax is equivalent to:

Example 1: Creating a List of Squares

Using list comprehension to generate a list of squares for numbers from 0 to 9:

Output:

Example 2: Filtering Items with Conditions

You can also add conditions to list comprehensions to filter items. For example, let’s create a list of even numbers from 0 to 9:

Output:

Example 3: Applying Functions in List Comprehension

You can apply a function to the items in the iterable. Let’s say we want to convert a list of strings to uppercase:

Output:

Example 4: Nested List Comprehensions

List comprehensions can be nested, allowing you to create lists of lists. For example, let’s create a 3×3 matrix:

Output:

Example 5: Flattening a Nested List

If you have a list of lists and you want to flatten it into a single list, you can use a nested list comprehension:

Output:

Summary

List comprehension is a highly efficient and Pythonic way to create and manipulate lists. It can simplify your code by reducing the need for multiple lines and loops, making it more readable and often more efficient. Whether you’re performing transformations, applying conditions, or generating lists from other lists, list comprehension is an essential tool in Python programming.

Share this Article
By Abhilash Jose Data Science Specialist
Follow:
Abhilash Jose is a data science specialist from India. He specializes in data analysis and is well-known for his expertise in areas such as machine learning and statistical modeling. His skills encompass a wide range of techniques, including data mining, predictive modeling, and data visualization.
Leave a comment