Sobes.tech
Senior

What are Python comprehensions? Can you give an example?

sobes.tech AI

Answer from AI

Python comprehensions are a concise and expressive way to create new collections (lists, sets, dictionaries) based on existing iterable objects with the ability to filter and transform elements.

Example of list comprehension creating a list of squares of numbers from 0 to 9:

squares = [x**2 for x in range(10)]
print(squares)  # [0, 1, 4, 9, 16, 25, 36, 49, 64, 81]

There are also set comprehensions, dict comprehensions, and generator expressions. They allow writing code more concisely and readably.