List, Set, and Dict Comprehensions for Concise Data Structures in Python


Use comprehensions to create data structures in a concise way.

Source Code

# List comprehension
squares = [x**2 for x in range(10)]
# Set comprehension
unique_squares = {x**2 for x in [-5, -4, -3, 3, 4, 5]}
# Dict comprehension
square_dict = {x: x**2 for x in range(5)}
Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments