Sobes.tech
Junior — Middle

Can you explain what list comprehension in Python is and how it is used?

sobes.tech AI

Answer from AI

List comprehensions in Python are a compact and convenient way to create lists based on existing iterable objects. They allow you to write a loop and a condition in a single line, making the code more readable and concise.

General syntax:

[expression for item in iterable if condition]

Example: create a list of squares of even numbers from 0 to 9:

squares = [x**2 for x in range(10) if x % 2 == 0]
print(squares)  # [0, 4, 16, 36, 64]

List comprehensions are widely used for filtering, transforming data, and simplifying code, replacing more verbose loops and conditional statements.