Blog Datasheets Home About me Clients My work Services Contact

G2Labs Grzegorz Grzęda

List comprehension in Python

February 1, 2024

List comprehension in Python is a concise and efficient way to create lists. It’s a single line of code that can replace multiple lines of loops and conditional statements. Here’s a basic overview and some examples to help you understand list comprehension.

Basic Structure

The basic structure of a list comprehension is:

1
[expression for item in iterable if condition]

Examples

  1. Simple List Comprehension:

    1
    2
    
    # Create a list of squares for numbers from 0 to 9
    squares = [x**2 for x in range(10)]
    
  2. List Comprehension with Condition:

    1
    2
    
    # Create a list of squares for even numbers from 0 to 9
    even_squares = [x**2 for x in range(10) if x % 2 == 0]
    
  3. Nested List Comprehension:

    1
    2
    3
    
    # Flatten a matrix (2D list) into a 1D list
    matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
    flattened = [num for row in matrix for num in row]
    
  4. List Comprehension with if-else:

    1
    2
    
    # Create a list where even numbers are squared, and odd numbers are negated
    mixed = [x**2 if x % 2 == 0 else -x for x in range(10)]
    
  5. Using List Comprehension with Functions:

    1
    2
    3
    4
    5
    
    # Applying a function to each item in a list
    def square(x):
        return x * x
    
    squares = [square(x) for x in range(10)]
    

Advantages

Points to Remember

List comprehensions are a powerful feature in Python that can help you write cleaner and more efficient code. As you practice, you’ll find them increasingly intuitive and useful in a variety of scenarios.


➡️ Getting Started with C Programming for AVR Atmega-328


⬅️ Introduction to AVR Assembly Language Programming with Atmega-328


Go back to Posts.