Sobes.tech
Junior — Middle

Can you explain the principle of list comprehension in Python?

sobes.tech AI

Answer from AI

List comprehension in Python is a concise way to create lists based on existing iterable objects with the possibility of filtering and transforming elements.

The syntax looks like this:

[expression for item in iterable if condition]

Example: creating 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)  # Outputs: [0, 4, 16, 36, 64]

This is a more readable and compact way compared to using for loops and conditional statements to create new lists.