what is a list comprehension?
A List Comprehension is a simple way to make a list from an iterable with one line.
preview
I have these tests by the end of the chapter
1import random
2import src.list_comprehensions
3import unittest
4
5
6def process(number):
7 return number ** 2
8
9
10def condition(number):
11 return number % 2 == 0
14class TestListComprehensions(unittest.TestCase):
15
16 def setUp(self):
17 self.a_list = []
18 self.an_iterable = range(0, random.randint(2, 1000))
19
20 def test_making_a_list_w_a_for_loop(self):
21 for number in self.an_iterable:
22 self.a_list.append(number)
23
24 self.assertEqual(self.a_list, list(self.an_iterable))
25 self.assertEqual(
26 src.list_comprehensions.a_for_loop(self.an_iterable),
27 self.a_list
28 )
30 def test_making_a_list_w_extend(self):
31 self.assertIsNone(self.a_list.extend(self.an_iterable))
32 self.assertEqual(self.a_list, list(self.an_iterable))
33
34 def test_making_a_list_w_a_list_comprehension(self):
35 self.assertEqual(
36 list(self.an_iterable),
37 [item for item in self.an_iterable]
38 )
39 self.assertEqual(
40 src.list_comprehensions.a_list_comprehension(
41 self.an_iterable
42 ),
43 [item for item in self.an_iterable]
44 )
46 def test_making_a_list_w_conditions(self):
47 even_numbers, odd_numbers = [], []
48 for item in self.an_iterable:
49 if condition(item):
50 even_numbers.append(item)
51 else:
52 odd_numbers.append(item)
53
54 self.assertEqual(
55 even_numbers,
56 [
57 item for item in self.an_iterable
58 if condition(item)
59 ]
60 )
61 self.assertEqual(
62 src.list_comprehensions.get_even_numbers(
63 self.an_iterable,
64 ),
65 [
66 item for item in self.an_iterable
67 if condition(item)
68 ]
69 )
70
71 self.assertEqual(
72 odd_numbers,
73 [
74 item for item in self.an_iterable
75 if not condition(item)
76 ]
77 )
78 self.assertEqual(
79 src.list_comprehensions.get_odd_numbers(
80 self.an_iterable
81 ),
82 [
83 item for item in self.an_iterable
84 if not condition(item)
85 ]
86 )
88 def test_making_a_list_w_processes(self):
89 square_club = []
90 for item in self.an_iterable:
91 square_club.append(process(item))
92
93 self.assertEqual(
94 square_club,
95 [process(item) for item in self.an_iterable]
96 )
97 self.assertEqual(
98 src.list_comprehensions.square(self.an_iterable),
99 [process(item) for item in self.an_iterable]
100 )
102 def test_making_a_list_w_processes_and_conditions(self):
103 even_squares, odd_squares = [], []
104 for item in self.an_iterable:
105 if condition(item):
106 even_squares.append(process(item))
107 else:
108 odd_squares.append(process(item))
109
110 self.assertEqual(
111 even_squares,
112 [
113 process(item)
114 for item in self.an_iterable
115 if condition(item)
116 ]
117 )
118 self.assertEqual(
119 odd_squares,
120 [
121 process(item)
122 for item in self.an_iterable
123 if not condition(item)
124 ]
125 )
126
127
128# Exceptions seen
129# AssertionError
130# NameError
131# AttributeError
132# TypeError
questions about list comprehensions
start the project
I open a terminal
I give
list_comprehensionsas the first argument to the makePythonTdd programthe terminal is my friend, and shows AssertionError
======================== FAILURES ========================== ______________ Testlist_comprehensions.test_failure _________________ self = <tests.test_list_comprehensions.Testlist_comprehensions testMethod=test_failure> def test_failure(self): > self.assertFalse(True) E AssertionError: True is not false tests/test_list_comprehensions.py:7: AssertionError ================== short test summary info ================== FAILED tests/test_list_comprehensions.py::Testlist_comprehensions::test_failure - AssertionError: True is not false ===================== 1 failed in X.YZs =====================I open
tests/test_list_comprehensions.pyfrom thetestsfolderI change assertFalse to assertTrue
4class Testlist_comprehensions(unittest.TestCase): 5 6 def test_failure(self): 7 self.assertTrue(True) 8 9 10# Exceptions seenthe test passes.
I change
Testlist_comprehensionstoTestListComprehensionsto match Python conventionI open a new terminal then change directory to
list_comprehensionsI add a git commit message
test_making_a_list_w_a_for_loop
I can make a list with the list constructor or with square brackets ([]). I can also add items to a list one at a time with the append method.
RED: make it fail
I change test_failure to test_making_a_list_w_a_for_loop to show what happens when I use the append method with more than one item
4class TestListComprehensions(unittest.TestCase):
5
6 def test_making_a_list_w_a_for_loop(self):
7 a_list = []
8 a_list.append(0)
9 a_list.append(1)
10 a_list.append(2)
11 a_list.append(3)
12 a_list.append(4)
13 a_list.append(5)
14 a_list.append(6)
15 a_list.append(7)
16 a_list.append(8)
17 a_list.append(9)
18 self.assertEqual(a_list, [])
19
20
21# Exceptions seen
22# AssertionError
the terminal is my friend, and shows AssertionError
GREEN: make it pass
I change the expectation to match
16 a_list.append(8)
17 a_list.append(9)
18 self.assertEqual(
19 a_list,
20 [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
21 )
22
23
24# Exceptions seen
25# AssertionError
the test passes.
REFACTOR: make it better
what is a for loop?
I just called the append method 10 times in a row, the only things that changed were the numbers I added to the list, there is a better way. I can use a for loop.
A for loop is a way to repeat the same command over an iterable (a collection of items), it is written like this
for item in collection:
do something
do something will run as many times as there are items in the collection.
I add a for loop to test_making_a_list_w_a_for_loop
6 def test_making_a_list_w_a_for_loop(self): 7 a_list = [] 8 # a_list.append(0) 9 # a_list.append(1) 10 # a_list.append(2) 11 # a_list.append(3) 12 # a_list.append(4) 13 # a_list.append(5) 14 # a_list.append(6) 15 # a_list.append(7) 16 # a_list.append(8) 17 # a_list.append(9) 18 19 for number in (0, 1, 2, 3, 4, 5, 6, 7, 8, 9): 20 a_list.append(number) 21 22 self.assertEqual( 23 a_list, 24 [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] 25 )the test is still green.
I remove the commented lines
6 def test_making_a_list_w_a_for_loop(self): 7 a_list = [] 8 for number in (0, 1, 2, 3, 4, 5, 6, 7, 8, 9): 9 a_list.append(number) 10 11 self.assertEqual( 12 a_list, 13 [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] 14 ) 15 16 17# Exceptions seenfor number in (0, 1, 2, 3, 4, 5, 6, 7, 8, 9):goes over every number in the tuplea_list.append(number)adds each number from the tuple toa_list
This for loop removed 10 lines of code and I can use it for any number of items, the other way gets busy very quickly once I have to add more numbers.
I add the range object for
(0, 1, 2, 3, 4, 5, 6, 7, 8, 9)6 def test_making_a_list_w_a_for_loop(self): 7 a_list = [] 8 # for number in (0, 1, 2, 3, 4, 5, 6, 7, 8, 9): 9 for number in range(10): 10 a_list.append(number)the test is still green.
I remove the commented line
6 def test_making_a_list_w_a_for_loop(self): 7 a_list = [] 8 for number in range(10): 9 a_list.append(number)range(10)makes a range object that goes from the0to the given number minus1, in this case it goes from0to9.The for loop is simpler than calling the append method for each item I want to add to a list, and there is an easier way. I can do the same thing with the list constructor since it takes an iterable as input
11 self.assertEqual( 12 a_list, 13 [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] 14 ) 15 self.assertEqual(list(), a_list) 16 17 18# Exceptions seenthe terminal is my friend, and shows AssertionError
I add the range object as input to the list constructor
15 self.assertEqual(list(range(0, 10)), a_list)the test passes.
I add a variable for
range(10)I use the variable for
range(10)andrange(0, 10)since they are the same6 def test_making_a_list_w_a_for_loop(self): 7 a_list = [] 8 numbers = range(10) 9 10 for number in numbers: 11 a_list.append(number) 12 13 self.assertEqual( 14 a_list, 15 [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] 16 ) 17 self.assertEqual(list(numbers), a_list) 18 19 20# Exceptions seenthe test is still green.
I add another assertion
17 self.assertEqual(list(numbers), a_list) 18 self.assertEqual( 19 src.list_comprehensions.a_for_loop(numbers), 20 [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] 21 ) 22 23 24# Exceptions seenI add NameError to the list of Exceptions seen
I add an import statement at the top of the file
1import src.list_comprehensions 2import unittestthe terminal is my friend, and shows AttributeError
I add AttributeError to the list of Exceptions seen
I open
__init__.pyfrom thelist_comprehensionsfolder in thesrcfolderI change the text in
src/list_comprehensions/__init__.pyto a functionI add TypeError to the list of Exceptions seen, in
tests/test_list_comprehensions.pyI add a name for the argument in
src/list_comprehensions/__init__.py1def a_for_loop(an_iterable): 2 return Nonethe terminal is my friend, and shows AssertionError
I change the return statement to match
1def a_for_loop(an_iterable): 2 return [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]the test passes. The problem with this solution is that it will fail when I have a range of numbers that is different. I want a solution that can take any iterable and return the right list
how to use random numbers
I want to add randomness to the test to make sure the function can handle any iterable I give as input.
I can do that with the random module from The Python Standard Library which is used to make fake random numbers.
I import the random module to use random numbers in
tests/test_list_comprehensions.pyI change the second value in the parentheses for the range object to a random number
8 def test_making_a_list_w_a_for_loop(self): 9 a_list = [] 10 numbers = range(random.randint(2, 1000)) 11 12 for number in numbers:the terminal is my friend, and shows AssertionError
random.randint(2, 1000)gives me a random integer between the first number in parentheses and the second number minus1, in this case the number can be anything from2to999this range object now goes from
0to anywhere between1and999because it goes from0to the given number minus1, and the given number in this case is a random integer that can be anything from2to999
I hit ctrl+s a few times on the keyboard to run the tests and the values change every time the test runs
I change the expectation in the first assertion
12 for number in numbers: 13 a_list.append(number) 14 15 self.assertEqual(a_list, list(numbers)) 16 self.assertEqual(list(numbers), a_list) 17 self.assertEqual( 18 src.list_comprehensions.a_for_loop(numbers), 19 [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] 20 )the test passes.
I remove the second assertion because it is now a repetition
I change the expectation of the second assertion
15 self.assertEqual(a_list, list(numbers)) 16 self.assertEqual( 17 src.list_comprehensions.a_for_loop(numbers), 18 a_list 19 ) 20 21 22# Exceptions seenthe terminal is my friend, and shows AssertionError
I change the function in
src/list_comprehensions/__init__.py1def a_for_loop(an_iterable): 2 result = [] 3 for stuff in an_iterable: 4 result.append(stuff) 5 return result 6 return [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]the test passes.
I remove the second return statement
I add a git commit message
I know how to make a list with a for loop. Why did I use a for loop when I can use the list constructor to do the same thing with less characters? Sometimes one is better than the other
test_making_a_list_w_extend
I can also use the extend method to make a list from an iterable
RED: make it fail
I add a test for making a list with the extend method
16 self.assertEqual(
17 src.list_comprehensions.a_for_loop(numbers),
18 a_list
19 )
20
21 def test_making_a_list_w_extend(self):
22 a_list = []
23 a_range = range(0, random.randint(2, 1000))
24 self.assertIsNone(a_list.extend())
25
26
27# Exceptions seen
GREEN: make it pass
I add the iterable
24 self.assertIsNone(a_list.extend(a_range))
the test is green again because the extend method returns None.
REFACTOR: make it better
I add another assertion to see what changed in the list
21 def test_making_a_list_w_extend(self): 22 a_list = [] 23 a_range = range(0, random.randint(2, 1000)) 24 self.assertIsNone(a_list.extend(a_range)) 25 self.assertEqual(a_list, list()) 26 27 28# Exceptions seenthe terminal is my friend, and shows AssertionError
I change the expectation
24 self.assertIsNone(a_list.extend(a_range)) 25 self.assertEqual(a_list, list(a_range)) 26 27 28# Exceptions seenthe test passes. extend uses less lines than the for loop and is not better than the list constructor.
I made the same variables twice, one for the empty list and one for the iterable, I add object attributes to remove the repetition
I use the new object attributes in test_making_a_list_w_a_for_loop
11 def test_making_a_list_w_a_for_loop(self): 12 # a_list = [] 13 # numbers = range(random.randint(2, 1000)) 14 15 # for number in numbers: 16 for number in self.an_iterable: 17 # a_list.append(number) 18 self.a_list.append(number) 19 20 # self.assertEqual(a_list, list(numbers)) 21 self.assertEqual(self.a_list, list(self.an_iterable)) 22 self.assertEqual( 23 # src.list_comprehensions.a_for_loop(numbers), 24 src.list_comprehensions.a_for_loop(self.an_iterable), 25 # a_list 26 self.a_list 27 ) 28 29 def test_making_a_list_w_extend(self):the test is still green.
I remove the commented lines from test_making_a_list_w_a_for_loop
11 def test_making_a_list_w_a_for_loop(self): 12 for number in self.an_iterable: 13 self.a_list.append(number) 14 15 self.assertEqual(self.a_list, list(self.an_iterable)) 16 self.assertEqual( 17 src.list_comprehensions.a_for_loop(self.an_iterable), 18 self.a_list 19 ) 20 21 def test_making_a_list_w_extend(self):I use the object attributes in test_making_a_list_w_extend
21 def test_making_a_list_w_extend(self): 22 # a_list = [] 23 # a_range = range(0, random.randint(2, 1000)) 24 # self.assertIsNone(a_list.extend(a_range)) 25 self.assertIsNone(self.a_list.extend(self.an_iterable)) 26 # self.assertEqual(a_list, list(a_range)) 27 self.assertEqual(self.a_list, list(self.an_iterable)) 28 29 30# Exceptions seenthe terminal is my friend, and shows AssertionError
AssertionError: Lists differ: [0, 1, 2, 3, ... XYZ, 0, 1, 2, 3, ...XYZ] != [0, 1, 2, 3, ...XYZ]the values in
a_listare double what the assertion expects. I broke something by using the object attributesI change
a_listback21 def test_making_a_list_w_extend(self): 22 a_list = [] 23 # a_range = range(0, random.randint(2, 1000)) 24 # self.assertIsNone(a_list.extend(a_range)) 25 self.assertIsNone(a_list.extend(self.an_iterable)) 26 # self.assertEqual(a_list, list(a_range)) 27 self.assertEqual(a_list, list(self.an_iterable)) 28 29 30# Exceptions seenthe test is green again.
I add a git commit message
how to use the setUp method to reset object attributes for every test
The problem is that both tests append to self.a_list. I was making an empty list for each test before.
The unittest.TestCase class has a method I can use to make sure the object attributes are always reset at the beginning of the test, so that the values are new for each test.
RED: make it fail
I add the setUp method to the
TestListComprehensionsobject and move the object attributes into it6class TestListComprehensions(unittest.TestCase): 7 8 def setUp(self): 9 a_list = [] 10 an_iterable = range(0, random.randint(2, 1000)) 11 12 def test_making_a_list_w_a_for_loop(self):the terminal is my friend, and shows AttributeError
FAILED ...test_making_a_list_w_a_for_loop - AttributeError: 'TestListComprehensions' object has no attribute 'an_iterable' FAILED ...test_making_a_list_w_extend - AttributeError: 'TestListComprehensions' object has no attribute 'an_iterable'because the other methods can not reach the
an_iterablevariable from outside the setUp method. I have to make it an object attribute.
GREEN: make it pass
I add
self.toan_iterablein the setUp method to make it an object attribute8 def setUp(self): 9 a_list = [] 10 self.an_iterable = range(0, random.randint(2, 1000)) 11 12 def test_making_a_list_w_a_for_loop(self):the terminal is my friend, and shows AttributeError
because the other methods can not reach the
a_listvariable from outside the setUp method. I have to make it an object attribute.I add
self.toa_listin the setUp method to make it an object attribute8 def setUp(self): 9 self.a_list = [] 10 self.an_iterable = range(0, random.randint(2, 1000))the test is green again.
The unittest.TestCase.setUp method runs before every test, in this case it sets these object attributes (variables)
self.a_listto an empty listself.an_iterableto a range object that goes from0to random number between1and999
REFACTOR: make it better
I try to use
self.a_listagain in test_making_a_list_w_extend22 def test_making_a_list_w_extend(self): 23 # a_list = [] 24 # a_range = range(0, random.randint(2, 1000)) 25 # self.assertIsNone(a_list.extend(a_range)) 26 # self.assertIsNone(a_list.extend(self.an_iterable)) 27 self.assertIsNone(self.a_list.extend(self.an_iterable)) 28 # self.assertEqual(a_list, list(a_range)) 29 # self.assertEqual(a_list, list(self.an_iterable)) 30 self.assertEqual(self.a_list, list(self.an_iterable)) 31 32 33# Exceptions seenthe test is still green.
I remove the commented lines from test_making_a_list_w_extend
I add a git commit message
test_making_a_list_w_a_list_comprehension
I can use a list comprehension to make a list from an iterable with one line.
RED: make it fail
I add a failing test
24 self.assertEqual(self.a_list, list(self.an_iterable))
25
26 def test_making_a_list_w_a_list_comprehension(self):
27 self.assertEqual(
28 list(self.an_iterable),
29 []
30 )
31
32
33# Exceptions seen
the terminal is my friend, and shows AssertionError
GREEN: make it pass
I add a list comprehension as the expectation
26 def test_making_a_list_w_a_list_comprehension(self):
27 self.assertEqual(
28 list(self.an_iterable),
29 [item for item in self.an_iterable]
30 )
31
32
33# Exceptions seen
the test passes.
Note
A list comprehension is like a for loop without the append line, for example
a_list = []
for item in iterable:
a_list.append(item)
is the same as this list comprehension
a_list = [item for item in iterable]
item comes before for item in the list comprehension
a_list = [] vs a_list = [
for item in iterable: vs item
a_list.append(item) vs for item in iterable]
and it is NOT
a_list = [a_list.append(item) for item in iterable]
because that would be saying a_list two times.
REFACTOR: make it better
I add another assertion for practice
27 self.assertEqual( 28 list(self.an_iterable), 29 [item for item in self.an_iterable] 30 ) 31 self.assertEqual( 32 src.list_comprehensions.a_list_comprehension(self.an_iterable), 33 [item for item in self.an_iterable] 34 ) 35 36 37# Exceptions seenthe terminal is my friend, and shows AttributeError
I add the function to
src/list_comprehensions/__init__.py1def a_for_loop(a_container): 2 result = [] 3 for stuff in a_container: 4 result.append(stuff) 5 return result 6 7 8def a_list_comprehension(a_collection): 9 return [element for element in a_collection]the test passes.
I add a git commit message
I made 2 functions that do the same thing - one uses a for loop and the other uses a list comprehension
result = []
for stuff in a_container:
result.append(stuff)
and
[element for element in a_collection]
the difference between them is that in the first case I have to
with the list comprehension, I do all the steps in one line.
So far none of the other ways are better than using the list constructor, yet.
test_making_a_list_w_conditions
What if I had to make a list from an iterable based on a condition?
RED: make it fail
I add a failing test to tests/test_list_comprehensions.py
31 self.assertEqual(
32 src.list_comprehensions.a_list_comprehension(
33 self.an_iterable
34 ),
35 [item for item in self.an_iterable]
36 )
37
38 def test_making_a_list_w_conditions(self):
39 even_numbers = []
40 for item in self.an_iterable:
41 if item % 2 == 0:
42 even_numbers.append(item)
43
44 self.assertEqual(
45 even_numbers,
46 list(self.an_iterable)
47 )
48
49
50# Exceptions seen
the terminal is my friend, and shows AssertionError
the numbers on the left are even numbers from the iterable, and the numbers on the right are every number in the iterable
if item % 2 == 0:checks if the number inself.an_iterableleaves a remainder of0when it is divided by2(the rule for even numbers).%is the modulo operator, which divides the number on the left by the number on the right and returns a remainder, there is a test for it in test_the_modulo_operation.
GREEN: make it pass
How can I make the
even_numberslist with the list constructor without changing the iterable? Since I can make the list with a for loop, I can do it with a list comprehension. I change the expectation44 self.assertEqual( 45 even_numbers, 46 [item for item in self.an_iterable] 47 ) 48 49 50# Exceptions seenthe terminal still shows AssertionError
I add the if statement to the list comprehension
44 self.assertEqual( 45 even_numbers, 46 [ 47 item for item in self.an_iterable 48 if item % 2 == 0 49 ] 50 ) 51 52 53# Exceptions seenthe test passes. This is a case where a list comprehension or a for loop is better than using the list constructor.
REFACTOR: make it better
I add another assertion to practice
44 self.assertEqual( 45 even_numbers, 46 [ 47 item for item in self.an_iterable 48 if item % 2 == 0 49 ] 50 ) 51 self.assertEqual( 52 src.list_comprehensions.get_even_numbers( 53 self.an_iterable 54 ), 55 [ 56 item for item in self.an_iterable 57 if item % 2 == 0 58 ] 59 ) 60 61 62# Exceptions seenthe terminal is my friend, and shows AttributeError
I add a function to
src/list_comprehensions/__init__.py8def a_list_comprehension(a_collection): 9 return [element for element in a_collection] 10 11 12def get_even_numbers(numbers): 13 return [ 14 number for number in numbers 15 if number % 2 == 0 16 ]the test passes.
I wrote the same condition in the test three times. I have to make the same change everywhere I wrote it if I want to change it. Let us say the new condition is that the number should be divisible by
3. I make the change intests/test_list_comprehensions.py38 def test_making_a_list_w_conditions(self): 39 even_numbers = [] 40 for item in self.an_iterable: 41 if item % 3 == 0: 42 even_numbers.append(item)the terminal is my friend, and shows AssertionError
I change the condition in the list comprehension of the first assertion
44 self.assertEqual( 45 even_numbers, 46 [ 47 item for item in self.an_iterable 48 if item % 3 == 0 49 ] 50 )the test is green again
I change the condition in the list comprehension of the second assertion
51 self.assertEqual( 52 src.list_comprehensions.get_even_numbers( 53 self.an_iterable 54 ), 55 [ 56 item for item in self.an_iterable 57 if item % 3 == 0 58 ] 59 ) 60 61 62# Exceptions seenthe terminal is my friend, and shows AssertionError
I change the condition in the
get_even_numbersfunction insrc/list_comprehensions/__init__.py12def get_even_numbers(numbers): 13 return [ 14 number for number in numbers 15 if number % 3 == 0 16 ]the test passes.
I add a function to remove the repetition, in
tests/test_list_comprehensions.pyI change the if statement in test_making_a_list_w_conditions to call the new function
42 def test_making_a_list_w_conditions(self): 43 even_numbers = [] 44 for item in self.an_iterable: 45 # if item % 3 == 0: 46 if condition(item): 47 even_numbers.append(item)the test is still green.
I remove the commented line and use the new function in the first assertion
42 def test_making_a_list_w_conditions(self): 43 even_numbers = [] 44 for item in self.an_iterable: 45 if condition(item): 46 even_numbers.append(item) 47 48 self.assertEqual( 49 even_numbers, 50 [ 51 item for item in self.an_iterable 52 # if item % 3 == 0 53 if condition(item) 54 ] 55 )still green.
I remove the commented line and use the new function in the next assertion
48 self.assertEqual( 49 even_numbers, 50 [ 51 item for item in self.an_iterable 52 if condition(item) 53 ] 54 ) 55 self.assertEqual( 56 src.list_comprehensions.get_even_numbers( 57 self.an_iterable 58 ), 59 [ 60 item for item in self.an_iterable 61 # if item % 3 == 0 62 if condition(item) 63 ] 64 )green.
I remove the commented line
55 self.assertEqual( 56 src.list_comprehensions.get_even_numbers( 57 self.an_iterable 58 ), 59 [ 60 item for item in self.an_iterable 61 if condition(item) 62 ] 63 ) 64 65 66# Exceptions seenNote
conditionis NOT a good name for a function because it is too general, it does not tell what it does. I use it to show that I think of a list comprehension as[item for item in iterable if condition]I change the condition in the new function
6def condition(number): 7 return number % 2 == 0 8 9 10class TestListComprehensions(unittest.TestCase):the terminal is my friend, and shows AssertionError
I change the condition in
get_even_numbersinsrc/list_comprehensions/__init__.py12def get_even_numbers(numbers): 13 return [ 14 number for number in numbers 15 if number % 2 == 0 16 ]the test passes.
The addition of the
conditionfunction adds extra lines to the test file.It also makes it easier to manage the code because I now only have to make a change in one place in the test when I need.
I add a new empty list to test another condition in
tests/test_list_comprehensions.py42 def test_making_a_list_w_conditions(self): 43 even_numbers, odd_numbers = [], [] 44 for item in self.an_iterable:even_numbers, odd_numbers = [], []makes 2 empty lists and names themI add an else clause to the if statement in the for loop
42 def test_making_a_list_w_conditions(self): 43 even_numbers, odd_numbers = [], [] 44 for item in self.an_iterable: 45 if condition(item): 46 even_numbers.append(item) 47 else: 48 odd_numbers.append(item) 49 50 self.assertEqual( 51 even_numbers,I add an assertion for the new list
57 self.assertEqual( 58 src.list_comprehensions.get_even_numbers( 59 self.an_iterable 60 ), 61 [ 62 item for item in self.an_iterable 63 if condition(item) 64 ] 65 ) 66 67 self.assertEqual( 68 odd_numbers, 69 [ 70 item for item in self.an_iterable 71 ] 72 ) 73 74 75# Exceptions seenthe terminal is my friend, and shows AssertionError
the numbers on the left are odd numbers from the iterable, and the numbers on the right are every number in the iterable.
I add the if statement to the assertion and negate the result of a call to the
conditionfunction67 self.assertEqual( 68 odd_numbers, 69 [ 70 item for item in self.an_iterable 71 if not condition(item) 72 ] 73 ) 74 75 76# Exceptions seenthe test passes.
I add another assertion
67 self.assertEqual( 68 odd_numbers, 69 [ 70 item for item in self.an_iterable 71 if not condition(item) 72 ] 73 ) 74 self.assertEqual( 75 src.list_comprehensions.get_odd_numbers( 76 self.an_iterable 77 ), 78 [ 79 item for item in self.an_iterable 80 if not condition(item) 81 ] 82 ) 83 84 85# Exceptions seenthe terminal is my friend, and shows AttributeError
- caption:
terminal
- AttributeError: module ‘src.list_comprehensions’
has no attribute ‘get_odd_numbers’. Did you mean: ‘get_even_numbers’?
I add the function to
src/list_comprehensions/__init__.py12def get_even_numbers(numbers): 13 return [ 14 number for number in numbers 15 if number % 2 == 0 16 ] 17 18 19def get_odd_numbers(numbers): 20 return [ 21 number for number in numbers 22 if number % 2 != 0 23 ]the test passes.
These two conditions are similar
if number % 2 == 0 if number % 2 != 0the difference is the equality symbols
==and!=I add a function to remove the repetition
I call the function in the
get_even_numbersfunction16def get_even_numbers(numbers): 17 return [ 18 number for number in numbers 19 if is_even(number) 20 ] 21 22 23def get_odd_numbers(numbers):the test is still green.
I negate the result of the call to the new function from the
get_odd_numbersfunction23def get_odd_numbers(numbers): 24 return [ 25 number for number in numbers 26 if not is_even(number) 27 ]still green.
another way to make a list based on a condition
There is a Python Built-in Function I can use to do the same thing as this list comprehension, it is called filter, which is a way to say “make a list based on a condition” or “give me only the things that meet this condition”.
I add a call to the filter built-in function it in the
get_even_numbersfunction16def get_even_numbers(numbers): 17 return filter(is_even, numbers) 18 return [ 19 number for number in numbers 20 if is_even(number) 21 ]the terminal is my friend, and shows AssertionError
I have to make the filter object a list.
I put it in the list constructor
16def get_even_numbers(numbers): 17 return list(filter(is_even, numbers)) 18 return [ 19 number for number in numbers 20 if is_even(number) 21 ]the test passes. Which do you like better: filter or the list comprehension?
filter takes a function as input, which means I would have to make one for odd numbers like
is_evenbecause I cannot pass itnot is_evenas input24def get_odd_numbers(numbers): 25 return list(filter(not is_even, numbers)) 26 return [ 27 number for number in numbers 28 if not is_even(number) 29 ]I do not want to write a new function. I can use a lambda function which is a function with no name to make it work
24def get_odd_numbers(numbers): 25 return list( 26 filter( 27 lambda number: not is_even(number), 28 numbers 29 ) 30 ) 31 return [ 32 number for number in numbers 33 if not is_even(number) 34 ]the test passes. This is not sexy.
another option is to use the filterfalse method from the itertools library, it is part of The Python Standard Library and needs an import statement
24def get_odd_numbers(numbers): 25 import itertools 26 return list(itertools.filterfalse(is_even, numbers)) 27 return list( 28 filter( 29 lambda number: not is_even(number), 30 numbers 31 ) 32 ) 33 return [ 34 number for number in numbers 35 if not is_even(number) 36 ]the test is still green. filterfalse returns the items from the iterable that do not meet the condition of the function
I add a git commit message
Which of the options shown so far do you like? Which is simpler and easier to understand or remember?
test_making_a_list_w_processes
append is not the only operation I can do with a list comprehension.
RED: make it fail
I add a failing test to tests/test_list_comprehensions.py
74 self.assertEqual(
75 src.list_comprehensions.get_odd_numbers(
76 self.an_iterable
77 ),
78 [
79 item for item in self.an_iterable
80 if not condition(item)
81 ]
82 )
83
84 def test_making_a_list_w_processes(self):
85 square_club = []
86 for item in self.an_iterable:
87 square_club.append(item*item)
88
89 self.assertEqual(
90 square_club,
91 [item for item in self.an_iterable]
92 )
93
94
95# Exceptions seen
the terminal is my friend, and shows AssertionError
the numbers on the left are squares of the numbers on the right.
GREEN: make it pass
I add the calculation to the list comprehension
89 self.assertEqual(
90 square_club,
91 [item*item for item in self.an_iterable]
92 )
93
94
95# Exceptions seen
the test passes.
REFACTOR: make it better
I add another assertion
89 self.assertEqual( 90 square_club, 91 [item*item for item in self.an_iterable] 92 ) 93 self.assertEqual( 94 src.list_comprehensions.square(self.an_iterable), 95 [item*item for item in self.an_iterable] 96 ) 97 98 99# Exceptions seenthe terminal is my friend, and shows AttributeError
I add the function to
src/list_comprehensions/__init__.py33 return [ 34 number for number in numbers 35 if not is_even(number) 36 ] 37 38 39def square(numbers): 40 return [number**2 for number in numbers]the test passes.
x**yis how to writexraised to the power ofy\[x ^ y\]
another way to process a list
There is a Python Built-in Function that I can use to process a list, just like filter, this one is called map
I add a call to the map built-in function in the
squarefunction with a lambda function39def square(numbers): 40 return map(lambda number: number**2, numbers) 41 return [number**2 for number in numbers]the terminal is my friend, and shows AssertionError
I have to change the map object to a list.
I add the list constructor to the
squarefunction39def square(numbers): 40 return list(map(lambda number: number**2, numbers)) 41 return [number**2 for number in numbers]the test passes. map takes in a function as input. I still like the list comprehension better, it is simpler and easier to read
I add a function for the calculation I just did three times in
tests/test_list_comprehensions.pyI call the new function in the for loop in test_making_a_list_w_processes
88 def test_making_a_list_w_processes(self): 89 square_club = [] 90 for item in self.an_iterable: 91 # square_club.append(item*item) 92 square_club.append(process(item)) 93 94 self.assertEqual( 95 square_club, 96 [item*item for item in self.an_iterable] 97 )the test is still green.
I remove the commented line then call the new function in the first assertion of test_making_a_list_w_processes
88 def test_making_a_list_w_processes(self): 89 square_club = [] 90 for item in self.an_iterable: 91 square_club.append(process(item)) 92 93 self.assertEqual( 94 square_club, 95 # [item*item for item in self.an_iterable] 96 [process(item) for item in self.an_iterable] 97 )still green.
I remove the commented line then call the new function in the second assertion of test_making_a_list_w_processes
93 self.assertEqual( 94 square_club, 95 [process(item) for item in self.an_iterable] 96 ) 97 self.assertEqual( 98 src.list_comprehensions.square(self.an_iterable), 99 # [item*item for item in self.an_iterable] 100 [process(item) for item in self.an_iterable] 101 ) 102 103 104# Exceptions seengreen.
I remove the commented line
I add a git commit message
Note
processis NOT a good name for a function because it is general, it does not tell what it does. I use it to show that I think of a list comprehension as[process(item) for item in iterable]
I know how to process (transform) a list with list comprehensions.
test_making_a_list_w_processes_and_conditions
I can use both processes and conditions in a list comprehension
RED: make it fail
I add a failing test
97 self.assertEqual(
98 src.list_comprehensions.square(self.an_iterable),
99 [process(item) for item in self.an_iterable]
100 )
101
102 def test_making_a_list_w_processes_and_conditions(self):
103 even_squares, odd_squares = [], []
104 for item in self.an_iterable:
105 if condition(item):
106 even_squares.append(process(item))
107 else:
108 odd_squares.append(process(item))
109
110 self.assertEqual(
111 even_squares,
112 [item for item in self.an_iterable]
113 )
114
115
116# Exceptions seen
the terminal is my friend, and shows AssertionError
the numbers on the left are the squares of the even numbers on the right.
GREEN: make it pass
I add a call to the
conditionfunction110 self.assertEqual( 111 even_squares, 112 [item for item in self.an_iterable if condition(item)] 113 )the terminal is my friend, and shows AssertionError
the numbers on the left are squares of the numbers on the right
I add a call to the
processfunction, in test_making_a_list_w_processes_and_conditions110 self.assertEqual( 111 even_squares, 112 [ 113 process(item) 114 for item in self.an_iterable 115 if condition(item) 116 ] 117 ) 118 119 120# Exceptions seenthe test passes.
REFACTOR: make it better
I add another assertion
110 self.assertEqual( 111 even_squares, 112 [ 113 process(item) 114 for item in self.an_iterable 115 if condition(item) 116 ] 117 ) 118 self.assertEqual( 119 odd_squares, 120 [ 121 item for item in self.an_iterable 122 ] 123 ) 124 125 126# Exceptions seenthe terminal is my friend, and shows AssertionError
the numbers on the left are the squares of the odd numbers from the right.
I add a call to the
conditionfunction and negate the result118 self.assertEqual( 119 odd_squares, 120 [ 121 item for item in self.an_iterable 122 if not condition(item) 123 ] 124 ) 125 126 127# Exceptions seenthe terminal is my friend, and shows AssertionError
the numbers on the left are squares of the numbers on the right.
I add a call to the
processfunction118 self.assertEqual( 119 odd_squares, 120 [ 121 process(item) 122 for item in self.an_iterable 123 if not condition(item) 124 ] 125 ) 126 127 128# Exceptions seenthe test passes.
I add a git commit message
I can use functions and conditions with list comprehensions to make a list with one line. I think of it as
[
process(item)
for item in iterable
if condition/not condition
]
dict comprehensions
I can also do this with dictionaries, they are called dict comprehensions and the syntax is
{
a_process(key): another_process(value)
for key/value in iterable
if condition/not condition
}
generator expressions
There are also generator expressions, they are the same syntax as list comprehensions but with parentheses (()) instead of brackets ([])
(
process(item)
for item in iterable
if condition/not condition
)
close the project
I close
tests/test_list_comprehensions.pyandsrc/list_comprehensions/__init__.pyI click in the terminal, then use q on the keyboard to leave the tests
I change directory to the parent of
list_comprehensions
review
I ran tests to show I can make a list from an iterable with
list comprehensions where I can
How many questions can you answer after going through this chapter?
code from the chapter
what is next?
I know how to make a Python Test Driven Development environment manually.
I know how to make a Python Test Driven Development environment automatically.
I know how to make a Python Test Driven Development environment automatically with variables.
rate pumping python
If this has been a 7 star experience for you, please CLICK HERE to leave a 5 star review of pumping python. It helps other people get into the book too.