Tutorials
Search…
Lesson 19. Comprehensions
Comprehensions are another Python goodie that lets you write code in the functional programming paradigm. I am only going to talk about them here very lightly as functional programming is a bit beyond this tutorial. We will see them later in the solutions section.
A comprehension is another construct that allows you to loop over an iterable object. Specifically, it lets you iterate over lists, dictionaries, and sets which we have not talked about nor will we in this particular tutorial.
Comprehensions are a way to write Pythonic code. You can use comprehensions to take a lot of complex logic and reduce it to a line of code. Be aware that the return datatype of a comprehension is a list.

Comprehension Syntax

[[function] for x in [list, dict, or set]]

Examples

Example #1 A Different Kind Of Loop Redux
In this example we are going to take example #2 from lesson 17 and rewrite it as a comprehension.
#The original function using map.
count = [1,2,3,4,5]
newcount = list(map(lambda x: x + 1, count))
print(newcount)
#The new function using a comprehension.
count = [1,2,3,4,5]
newcount = [x + 1 for x in count]
print(newcount)

Now you try it!

Don't copy and past. Type the code yourself!
Copy link
On this page
Comprehension Syntax
Examples
Now you try it!