The Noobs of Python: Ep.3.2 - Lets Comprehend: Comprehensions!

Python language has a couple of methods for creating lists and dictionaries that are known
as comprehensions. There is also a third type of comprehension for creating a Python set, you will find that the comprehension constructs build on the knowledge you have acquired from the previous Ep's like The Noobs of Python: Ep.2.1 - List : Slice, Loops and more [Updated] as they contain loops and conditionals themselves.

Q: You've named a couple comprehensions, Which one are we going to start with?
A: Let's start with List Comprehensions !

List comprehensions are very useful. They can also be a bit hard to understand when and why you would use them. List comprehensions tend to be harder to read than just using a simple for loop as well, feel free to review some of the examples in The Noobs of Python: Ep.2.1 - List : Slice, Loops and more [Updated] in case you need a refresher.

A list comprehension is basically a one line for loop that produces a Python list data structure. List comprehensions evaluate an expression for each item in a list and return a list of the results. Think of this as a shortcut to apply an operation to every element in a list and get back a new list, without the pain of creating a temporary list. Here is an example fo a simple listcomp :

>>> level1 = ['wendell', 'kreestuh', 'ryan']
>>> L1T = [i.capitalize() for i in level1]
>>> print(L1T)
['Wendell', 'Kreestuh', 'Ryan']
>>>

This is a simple example of iterating over the list and using the capitalize() method to capitalize the list. By now we should be incorporating things we've learned in previous Ep's into our lessons for more practice. More of these in The Noobs of Python: Ep.3.0 - Methods to the Madness

Q: That was pretty simple but how is that broken down word by word?
A: Below is an example of the syntax for a basic list comprehension with some arguments aswell.

The most basic construction is [expression for var in list[for...|if...]]. This means that you can have multiple for and if statements after the initial construction. Lets say you’re parsing a file and looking for a particular word, You could use a list comprehension pseudo-filter of sorts:

>>>if [i for i in line if "Word" in i]:
>>>    do something

More examples in proceeding post below...

This is this initial post into List comprehensions to get the conversation going. There will be more post and examples moving us into Dict_Comps & Set_Comps in future Ep.3.x

Post your examples of List comps, or Parse out a text file using what you learn in The Noobs of Python: Ep.5.0 - File Manipulation by creating your own text file and using a list comp to filter words out.

Code_On_Code_Warrioirs

2 Likes

Let’s look at two for statements. Here, we extract each integer and pair it with each letter:

>>> num = [1, 2]
>>> alpha = ['a', 'b', 'c']
>>> l = [(i, x) for i in num for x in alpha]
>>> print(l)
[(1, 'a'), (1, 'b'), (1, 'c'), (2, 'a'), (2, 'b'), (2, 'c')]
>>>

Note that (i, x) is the pairing expression that operates on the results of the two for
expressions.

Post your samples below !

1 Like

Q: That last example was kinda cool ! What about using it to make a card deck?
A: I thought you'd never ask ! If you have any questions please post below !

>>> rank = ['A','K','Q','J','10','9','8','7','6','5','4','3','2','1']
>>> symbols = ['♥','♦','♠','♣']
>>> deck = [(i,x) for i in symbols for x in rank]
>>> print(deck)
[('♥', 'A'), ('♥', 'K'), ('♥', 'Q'), ('♥', 'J'), ('♥', '10'), 
('♥', '9'), ('♥', '8'), ('♥', '7'), ('♥', '6'), ('♥', '5'), ('♥', '4'), 
('♥', '3'), ('♥', '2'), ('♥', '1'), ('♦', 'A'), ('♦', 'K'), ('♦', 'Q'), 
('♦', 'J'), ('♦', '10'), ('♦', '9'), ('♦', '8'), ('♦', '7'), ('♦', '6'), 
('♦', '5'), ('♦', '4'), ('♦', '3'), ('♦', '2'), ('♦', '1'), ('♠', 'A'), 
('♠', 'K'), ('♠', 'Q'), ('♠', 'J'), ('♠', '10'), ('♠', '9'), ('♠', '8'), 
('♠', '7'), ('♠', '6'), ('♠', '5'), ('♠', '4'), ('♠', '3'), ('♠', '2'), 
('♠', '1'), ('♣', 'A'), ('♣', 'K'), ('♣', 'Q'), ('♣', 'J'), ('♣', '10'), 
('♣', '9'), ('♣', '8'), ('♣', '7'), ('♣', '6'), ('♣', '5'), ('♣', '4'), 
('♣', '3'), ('♣', '2'), ('♣', '1')]
>>>

Q: That card deck was cool, maybe in the future we can build a game with it !
Right now I have a simple math problem that ListComp might help me with? I need to get the square root of several numbers. Can we put the number in a list and do that?

A: Let's give that a try !

>>> num = [8, 12, 34, 5, 14, 91, 47]
>>> square = [x**2 for x in num]
>>> print(square)
[64, 144, 1156, 25, 196, 8281, 2209]
>>>

As you can see we used the variable square to iterate over the list num to get the square root of each value and return them in a list ! Pretty simple really,

Q: That was cool, but I should have said that i only need the square root of numbers divisible by 2 :wink:

A: That is still easy with ListComp ! Lets try this one more time using the example above:

>>> num = [8, 12, 34, 5, 14, 91, 47]
>>> 
>>> square_even = [x**2 for x in num if x % 2 == 0]
>>> print(square_even)
[64, 144, 1156, 196]
>>>

List comprehensions also support multiple if conditions. Multiple conditions at the same loop level are an implicit and expression:

>>> a = [1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> b = [x for x in a if x > 4 if x % 2 == 0]
>>> c = [x for x in a if x > 4 and x % 2 == 0]
>>> print(c)
[6, 8]
>>> print(b)
[6, 8]

Q: that was cool ! I'll have more questions later !
A: Plenty more to come, we will get into Dictionary comprehensions in the next Ep.3.3 here shortly !

Q: You mentioned that I need to start to use some of what I have learned in these Ep's with what I am trying to learn to solve problems, So Can I use List Comprehensions to create a multidimensional list, Place some values in the list and then at a later date use List Comprehension to filter the list?

A: Let's give it a try !
Note the examples in : The Noobs of Python: Ep.2.1 - List : Slice, Loops and more [Updated]

>>> A = ['stuff'] * 3
>>> for i in range(3):
	A[i] = ['stuff'] * 3
>>> A
[['stuff', 'stuff', 'stuff'], ['stuff', 'stuff', 'stuff'], ['stuff', 'stuff', 'stuff']]
>>> A[0][0] = 'HELLO'
>>> A[1][1] = 'WORLD'
>>> A[2][2] = '!!!'
>>> A
[['HELLO', 'stuff', 'stuff'], ['stuff', 'WORLD', 'stuff'], ['stuff', 'stuff', '!!!']]
>>> [i for x in A for i in x if i is not 'stuff']
['HELLO', 'WORLD', '!!!']
>>>