Research breakthrough possible @S-Logix pro@slogix.in

Office Address

Social List

What is List Comprehension in Python?

List Comprehension in Python

Condition for List Comprehension in Python

  • Description: List comprehension is a concise and efficient way to create lists in Python.It allows you to generate a new list by applying an expression to each item in an existing iterable and filtering elements based on a condition.
Step-by-Step Process
  • Start with an iterable (such as a list, range, etc.).
    Apply an expression to each item in the iterable.
    Include a condition (optional) to filter items.
    Syntax: [expression for item in iterable if condition]
Sample Code
  • # List comprehension
    print("Output for list comprehension to get squares of even numbers:")
    even_squares = [x ** 2 for x in range(1, 11) if x % 2 == 0]
    print(even_squares)
    print()
    print("Output for list comprehension to get vowels:")
    input_string = "Hello, World!"
    vowels = [char for char in input_string if char in 'aeiouAEIOU']
    print(vowels)
Screenshots
  • List Comprehension