Python Tutorial

Python Flow Control

Python Functions

Python Data Types

Python Date and Time

Python Files

Python String

Python List

Python Dictionary

Python Variable

Python Input/Output

Python Exceptions

Python Advanced

Python List Comprehension

In this Python List Comprehension tutorial, we'll cover the basics of list comprehensions, including their syntax and examples of how to use them.

List comprehensions are a concise and efficient way to create lists in Python. They offer a shorter syntax when you want to create a new list by applying an expression to each element in an iterable (e.g., list, tuple, string, etc.) or when you want to create a new list by filtering elements based on a condition.

Syntax

The basic syntax of a list comprehension is:

[expression for item in iterable if condition]
  • expression: The operation or transformation you want to apply to each item in the iterable.
  • item: A temporary variable representing each element in the iterable.
  • iterable: The original iterable (e.g., list, tuple, string, etc.) that you want to loop through.
  • if condition: (Optional) A filter to include only elements that meet a specific condition.

Examples

1. Basic List Comprehension

Create a list of the squares of the numbers from 0 to 9:

squares = [x ** 2 for x in range(10)]

print(squares)  # Output: [0, 1, 4, 9, 16, 25, 36, 49, 64, 81]

2. List Comprehension with a Condition

Create a list of even numbers from 0 to 9:

even_numbers = [x for x in range(10) if x % 2 == 0]

print(even_numbers)  # Output: [0, 2, 4, 6, 8]

3. List Comprehension with Nested Loops

Create a list of all possible pairs between two lists:

list1 = [1, 2, 3]
list2 = [4, 5, 6]

pairs = [(x, y) for x in list1 for y in list2]

print(pairs)
# Output: [(1, 4), (1, 5), (1, 6), (2, 4), (2, 5), (2, 6), (3, 4), (3, 5), (3, 6)]

4. List Comprehension with Nested Conditions

Create a list of all possible pairs between two lists, but only include pairs where the sum is greater than or equal to 7:

list1 = [1, 2, 3]
list2 = [4, 5, 6]

pairs = [(x, y) for x in list1 for y in list2 if x + y >= 7]

print(pairs)  # Output: [(1, 6), (2, 5), (2, 6), (3, 4), (3, 5), (3, 6)]

In this tutorial, you learned the basics of Python List Comprehensions, including their syntax and examples of how to use them to create new lists by applying expressions to elements in iterables and filtering elements based on conditions.

  1. How to use list comprehension in Python:

    • Description: List comprehension is a concise way to create lists using a single line of code.
    • Example Code:
      squares = [x**2 for x in range(1, 6)]
      print(squares)  # Output: [1, 4, 9, 16, 25]
      
  2. List comprehension vs traditional for loop in Python:

    • Description: List comprehension is a more compact and readable way to create lists compared to traditional for loops.
    • Example Code:
      # Using list comprehension
      squares = [x**2 for x in range(1, 6)]
      
      # Equivalent traditional for loop
      squares = []
      for x in range(1, 6):
          squares.append(x**2)
      
  3. Filtering elements with list comprehension in Python:

    • Description: List comprehension can include conditions to filter elements based on specific criteria.
    • Example Code:
      even_squares = [x**2 for x in range(1, 6) if x % 2 == 0]
      print(even_squares)  # Output: [4, 16]
      
  4. Nested list comprehension in Python:

    • Description: Nested list comprehension allows creating lists with multiple levels of iteration.
    • Example Code:
      matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
      flattened_matrix = [num for row in matrix for num in row]
      print(flattened_matrix)  # Output: [1, 2, 3, 4, 5, 6, 7, 8, 9]
      
  5. Creating lists with conditions using list comprehension:

    • Description: List comprehension can be used to create lists with conditions, such as filtering or transforming elements.
    • Example Code:
      words = ['apple', 'banana', 'cherry']
      short_words = [word.upper() for word in words if len(word) < 6]
      print(short_words)  # Output: ['APPLE', 'CHERRY']
      
  6. List comprehension with if-else in Python:

    • Description: List comprehension can include if-else statements for conditional expressions.
    • Example Code:
      numbers = [1, 2, 3, 4, 5]
      result = ['Even' if num % 2 == 0 else 'Odd' for num in numbers]
      print(result)  # Output: ['Odd', 'Even', 'Odd', 'Even', 'Odd']
      
  7. Examples of list comprehension in Python:

    • Description: Various examples showcasing the versatility of list comprehension for creating lists with different criteria.
    • Example Code:
      # Example 1: Squares of even numbers
      even_squares = [x**2 for x in range(1, 11) if x % 2 == 0]
      
      # Example 2: Convert strings to uppercase
      words = ['hello', 'world', 'python']
      uppercased_words = [word.upper() for word in words]
      
      # Example 3: Filtering positive numbers
      numbers = [1, -2, 3, -4, 5]
      positive_numbers = [num for num in numbers if num > 0]