Dict, list, and set comprehensions in Python provide a compact way to create dictionaries, lists, and sets based on specified expressions and conditions. They offer a concise and readable syntax for generating elements iteratively.
Example of list comprehension in Python: squares = [x**2 for x in range(10)] # Generates a list of squares from 0 to 9. The expression inside the square brackets is used to define the elements of the list.
Example list comprehension:
numbers = [1, 2, 3, 4, 5]
squared_numbers = [x**2 for x in numbers]
Example dict comprehension:
person = {'name': 'John', 'age': 30, 'city': 'New York'}
person_info = {key: value for key, value in person.items()}
Example set comprehension:
numbers = [1, 2, 2, 3, 4, 4, 5]
unique_numbers = {x for x in numbers}