Junior — Middle
Could you explain what is meant by 'comprehension' in Python programming language?
sobes.tech AI
Answer from AI
In Python, the term "comprehension" refers to a concise way of creating collections (lists, sets, dictionaries) using expressions that include a loop and a condition inside square brackets or other appropriate symbols.
For example, list comprehension allows creating a new list by applying an expression to each element and filtering them:
squares = [x**2 for x in range(5) if x % 2 == 0]
print(squares) # Outputs: [0, 4, 16]
This is a more concise and readable alternative to loops for creating collections.