The Solution to Your Python Problem Is a Probably a Comprehension

I got 99 problems and comprehensions solved all but one. --Not Jay Z

More times than I can count, I have looked up the best way to solve a problem in Python only to say, "Oh, a comprehension, I should have known."

What can you do with a comprehension?

You can filter things.

list2 = [x for x in list1 if x < 10]
set2 = {x for x in set1 if x < 10}
dict2 = {k: v for k, v in dict1.items() if v < 10}

You can find things.

item = next(x for x in list1 if x == 10)  # raises if not found
item = next((x for x in list1 if x == 10), None)  # returns None if not found

item = next(x for x in set1 if x == 10)
k, v = next((k, v) for k, v in dict1.items() if v == 10)

You can transform (map) things.

list2 = [x**2 for x in list1]
set2 = {x**2 for x in set1}
dict2 = {k: v**2 for k, v in dict1.items()}

And that's just scratching the surface. StackOverflow is a great place to see some unique problems you can solve with comprehensions.

Go forth and make comprehensions!