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

list_comprehensions/tests/test_list_comprehensions.py
 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
list_comprehensions/tests/test_list_comprehensions.py
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        )
list_comprehensions/tests/test_list_comprehensions.py
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        )
list_comprehensions/tests/test_list_comprehensions.py
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        )
list_comprehensions/tests/test_list_comprehensions.py
 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        )
list_comprehensions/tests/test_list_comprehensions.py
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_comprehensions as the first argument to the makePythonTdd program

    terminal
    ./makePythonTdd.sh list_comprehensions
    
    terminal
    .\makePythonTdd.ps1 list_comprehensions
    

    the terminal is my friend, and shows AssertionError

    terminal
    ======================== 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.py from the tests folder

  • I change assertFalse to assertTrue

    list_comprehensions/tests/test_list_comprehensions.py
     4class Testlist_comprehensions(unittest.TestCase):
     5
     6    def test_failure(self):
     7        self.assertTrue(True)
     8
     9
    10# Exceptions seen
    

    the test passes.

  • I change Testlist_comprehensions to TestListComprehensions to match Python convention

    list_comprehensions/tests/test_list_comprehensions.py
    1import unittest
    2
    3
    4class TestListComprehensions(unittest.TestCase):
    5
    6    def test_failure(self):
    
  • I open a new terminal then change directory to list_comprehensions

    terminal
    cd list_comprehensions
    
  • I add the new files and folder to git for tracking

    terminal
    git add .
    
  • I add a git commit message

    terminal
    git commit -am 'setup project'
    

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

terminal
AssertionError: Lists differ: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
                           != []

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

    list_comprehensions/tests/test_list_comprehensions.py
     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

    list_comprehensions/tests/test_list_comprehensions.py
     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 seen
    
    • for number in (0, 1, 2, 3, 4, 5, 6, 7, 8, 9): goes over every number in the tuple

    • a_list.append(number) adds each number from the tuple to a_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)

    list_comprehensions/tests/test_list_comprehensions.py
     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

    list_comprehensions/tests/test_list_comprehensions.py
    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 the 0 to the given number minus 1, in this case it goes from 0 to 9.

  • 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

    list_comprehensions/tests/test_list_comprehensions.py
    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 seen
    

    the terminal is my friend, and shows AssertionError

    terminal
    AssertionError: Lists differ: []
                               != [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
    
  • I add the range object as input to the list constructor

    list_comprehensions/tests/test_list_comprehensions.py
    15        self.assertEqual(list(range(0, 10)), a_list)
    

    the test passes.

  • I add a variable for range(10)

    list_comprehensions/tests/test_list_comprehensions.py
     6    def test_making_a_list_w_a_for_loop(self):
     7        a_list = []
     8        numbers = range(10)
     9
    10        for number in range(10):
    
  • I use the variable for range(10) and range(0, 10) since they are the same

    list_comprehensions/tests/test_list_comprehensions.py
     6    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 seen
    

    the test is still green.

  • I add another assertion

    list_comprehensions/tests/test_list_comprehensions.py
    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 seen
    

    the terminal is my friend, and shows NameError

    terminal
    NameError: name 'src' is not defined
    
  • I add NameError to the list of Exceptions seen

    list_comprehensions/tests/test_list_comprehensions.py
    24# Exceptions seen
    25# AssertionError
    26# NameError
    
  • I add an import statement at the top of the file

    1import src.list_comprehensions
    2import unittest
    

    the terminal is my friend, and shows AttributeError

    terminal
    AttributeError: module 'src.list_comprehensions'
                    has no attribute 'a_for_loop'
    
  • I add AttributeError to the list of Exceptions seen

  • I open __init__.py from the list_comprehensions folder in the src folder

  • I change the text in src/list_comprehensions/__init__.py to a function

    list_comprehensions/src/list_comprehensions/__init__.py
    1def a_for_loop():
    2    return None
    

    the terminal is my friend, and shows TypeError

    terminal
    TypeError: a_for_loop() takes 0 positional arguments
               but 1 was given
    
  • I add TypeError to the list of Exceptions seen, in tests/test_list_comprehensions.py

    list_comprehensions/tests/test_list_comprehensions.py
    25# Exceptions seen
    26# AssertionError
    27# NameError
    28# AttributeError
    29# TypeError
    
  • I add a name for the argument in src/list_comprehensions/__init__.py

    1def a_for_loop(an_iterable):
    2    return None
    

    the terminal is my friend, and shows AssertionError

    terminal
    AssertionError: None != [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
    
  • 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.py

    list_comprehensions/tests/test_list_comprehensions.py
    1import random
    2import src.list_comprehensions
    3import unittest
    
  • I change the second value in the parentheses for the range object to a random number

    list_comprehensions/tests/test_list_comprehensions.py
     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

    terminal
    AssertionError: Lists differ: [0, 1, 2, 3, ...]
                               != [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
    
    • random.randint(2, 1000) gives me a random integer between the first number in parentheses and the second number minus 1, in this case the number can be anything from 2 to 999

    • this range object now goes from 0 to anywhere between 1 and 999 because it goes from 0 to the given number minus 1, and the given number in this case is a random integer that can be anything from 2 to 999

  • 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

    list_comprehensions/tests/test_list_comprehensions.py
    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

    list_comprehensions/tests/test_list_comprehensions.py
    15        self.assertEqual(a_list, list(numbers))
    16        self.assertEqual(
    17            src.list_comprehensions.a_for_loop(numbers),
    18            [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
    19        )
    20
    21
    22# Exceptions seen
    
  • I change the expectation of the second assertion

    list_comprehensions/tests/test_list_comprehensions.py
    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 seen
    

    the terminal is my friend, and shows AssertionError

    terminal
    AssertionError: Lists differ: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
                               != [0, 1, 2, 3, ...]
    
  • I change the function in src/list_comprehensions/__init__.py

    1def 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

    terminal
    git commit -am \
    'add test_making_a_list_w_a_for_loop'
    

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

the terminal is my friend, and shows TypeError

terminal
TypeError: list.extend() takes exactly
           one argument (0 given)

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

    list_comprehensions/tests/test_list_comprehensions.py
    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 seen
    

    the terminal is my friend, and shows AssertionError

    terminal
    AssertionError: Lists differ: [0, 1, 2, 3, ...] != []
    
  • I change the expectation

    list_comprehensions/tests/test_list_comprehensions.py
    24        self.assertIsNone(a_list.extend(a_range))
    25        self.assertEqual(a_list, list(a_range))
    26
    27
    28# Exceptions seen
    

    the 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

    list_comprehensions/tests/test_list_comprehensions.py
     6class TestListComprehensions(unittest.TestCase):
     7
     8    a_list = []
     9    an_iterable = range(0, random.randint(2, 1000))
    10
    11    def test_making_a_list_w_a_for_loop(self):
    
  • I use the new object attributes in test_making_a_list_w_a_for_loop

    list_comprehensions/tests/test_list_comprehensions.py
    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

    list_comprehensions/tests/test_list_comprehensions.py
    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

    list_comprehensions/tests/test_list_comprehensions.py
    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 seen
    

    the terminal is my friend, and shows AssertionError

    terminal
    AssertionError: Lists differ: [0, 1, 2, 3, ... XYZ, 0, 1, 2, 3, ...XYZ] != [0, 1, 2, 3, ...XYZ]
    

    the values in a_list are double what the assertion expects. I broke something by using the object attributes

  • I change a_list back

    list_comprehensions/tests/test_list_comprehensions.py
    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(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 seen
    

    the test is green again.

  • I add a git commit message

    terminal
    git commit -am \
    'add test_making_a_list_w_extend'
    

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 TestListComprehensions object and move the object attributes into it

    list_comprehensions/tests/test_list_comprehensions.py
     6class 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

    terminal
    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_iterable variable from outside the setUp method. I have to make it an object attribute.


GREEN: make it pass


  • I add self. to an_iterable in the setUp method to make it an object attribute

    list_comprehensions/tests/test_list_comprehensions.py
     8    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

    terminal
    AttributeError: 'TestListComprehensions' object
                    has no attribute 'a_list'
    

    because the other methods can not reach the a_list variable from outside the setUp method. I have to make it an object attribute.

  • I add self. to a_list in the setUp method to make it an object attribute

    list_comprehensions/tests/test_list_comprehensions.py
     8    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_list to an empty list

    • self.an_iterable to a range object that goes from 0 to random number between 1 and 999


REFACTOR: make it better


  • I try to use self.a_list again in test_making_a_list_w_extend

    list_comprehensions/tests/test_list_comprehensions.py
    22    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 seen
    

    the test is still green.

  • I remove the commented lines from test_making_a_list_w_extend

    list_comprehensions/tests/test_list_comprehensions.py
    22    def test_making_a_list_w_extend(self):
    23        self.assertIsNone(self.a_list.extend(self.an_iterable))
    24        self.assertEqual(self.a_list, list(self.an_iterable))
    25
    26
    27# Exceptions seen
    
  • I add a git commit message

    terminal
    git commit -am 'add setUp method'
    

I know how to make a list with the extend method.


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

terminal
AssertionError: Lists differ: [0, 1, 2, 3, ...] != []

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

    list_comprehensions/tests/test_list_comprehensions.py
    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 seen
    

    the terminal is my friend, and shows AttributeError

    terminal
    AttributeError: module 'src.list_comprehensions'
                    has no attribute 'a_list_comprehension'
    
  • I add the function to src/list_comprehensions/__init__.py

    list_comprehensions/src/list_comprehensions/__init__.py
    1def 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

    terminal
    git commit -am \
    'add test_making_a_list_w_a_list_comprehension'
    

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.

I know how to use a list comprehension to make a list


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

list_comprehensions/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

terminal
AssertionError: Lists differ: [0, 2, 4, 6, 8, ...]
                           != [0, 1, 2, 3, 4, 5, 6, 7, 8...]

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 in self.an_iterable leaves a remainder of 0 when it is divided by 2 (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_numbers list 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 expectation

    list_comprehensions/tests/test_list_comprehensions.py
    44        self.assertEqual(
    45            even_numbers,
    46            [item for item in self.an_iterable]
    47        )
    48
    49
    50# Exceptions seen
    

    the terminal still shows AssertionError

    terminal
    AssertionError: Lists differ: [0, 2, 4, 6, 8, ...]
                               != [0, 1, 2, 3, 4, 5, 6, 7, 8...]
    
  • I add the if statement to the list comprehension

    list_comprehensions/tests/test_list_comprehensions.py
    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 seen
    

    the 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

    list_comprehensions/tests/test_list_comprehensions.py
    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 seen
    

    the terminal is my friend, and shows AttributeError

    terminal
    AttributeError: module 'src.list_comprehensions'
                    has no attribute 'get_even_numbers'
    
  • I add a function to src/list_comprehensions/__init__.py

    list_comprehensions/src/list_comprehensions/__init__.py
     8def 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 in tests/test_list_comprehensions.py

    list_comprehensions/tests/test_list_comprehensions.py
    38    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

    terminal
    AssertionError: Lists differ: [0, 3, 6, 9, ...]
                               != [0, 2, 4, 6, ...]
    
  • I change the condition in the list comprehension of the first assertion

    list_comprehensions/tests/test_list_comprehensions.py
    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

    list_comprehensions/tests/test_list_comprehensions.py
    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 seen
    

    the terminal is my friend, and shows AssertionError

    terminal
    AssertionError: Lists differ: [0, 2, 4, 6, ...]
                               != [0, 3, 6, 9, ...]
    
  • I change the condition in the get_even_numbers function in src/list_comprehensions/__init__.py

    list_comprehensions/src/list_comprehensions/__init__.py
    12def 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.py

    list_comprehensions/tests/test_list_comprehensions.py
     1import random
     2import src.list_comprehensions
     3import unittest
     4
     5
     6def condition(number):
     7    return number % 3 == 0
     8
     9
    10class TestListComprehensions(unittest.TestCase):
    
  • I change the if statement in test_making_a_list_w_conditions to call the new function

    list_comprehensions/tests/test_list_comprehensions.py
    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

    list_comprehensions/tests/test_list_comprehensions.py
    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

    list_comprehensions/tests/test_list_comprehensions.py
    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

    list_comprehensions/tests/test_list_comprehensions.py
    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 seen
    

    Note

    condition is 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

    list_comprehensions/tests/test_list_comprehensions.py
     6def condition(number):
     7    return number % 2 == 0
     8
     9
    10class TestListComprehensions(unittest.TestCase):
    

    the terminal is my friend, and shows AssertionError

    terminal
    AssertionError: Lists differ: [0, 3, 6, 9, ...]
                               != [0, 2, 4, 6, ...]
    
  • I change the condition in get_even_numbers in src/list_comprehensions/__init__.py

    list_comprehensions/src/list_comprehensions/__init__.py
    12def 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 condition function 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.py

    list_comprehensions/tests/test_list_comprehensions.py
    42    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 them

  • I add an else clause to the if statement in the for loop

    list_comprehensions/tests/test_list_comprehensions.py
    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

    list_comprehensions/tests/test_list_comprehensions.py
    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 seen
    

    the terminal is my friend, and shows AssertionError

    terminal
    AssertionError: Lists differ: [1, 3, 5, 7, ...]
                               != [0, 1, 2, 3, 4, 5, 6, 7, 8, ...]
    

    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 condition function

    list_comprehensions/tests/test_list_comprehensions.py
    67        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 seen
    

    the test passes.

  • I add another assertion

    list_comprehensions/tests/test_list_comprehensions.py
    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 seen
    

    the 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__.py

    list_comprehensions/src/list_comprehensions/__init__.py
    12def 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 != 0
    

    the difference is the equality symbols == and !=

    I add a function to remove the repetition

    list_comprehensions/src/list_comprehensions/__init__.py
     8def a_list_comprehension(a_collection):
     9    return [element for element in a_collection]
    10
    11
    12def is_even(number):
    13    return number % 2 == 0
    14
    15
    16def get_even_numbers(numbers):
    
  • I call the function in the get_even_numbers function

    list_comprehensions/src/list_comprehensions/__init__.py
    16def 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_numbers function

    list_comprehensions/src/list_comprehensions/__init__.py
    23def 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_numbers function

    list_comprehensions/src/list_comprehensions/__init__.py
    16def 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

    terminal
    AssertionError: <filter object at 0xffffab1c23d4>
                 != [0, 2, ...]
    

    I have to make the filter object a list.

  • I put it in the list constructor

    list_comprehensions/src/list_comprehensions/__init__.py
    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_even because I cannot pass it not is_even as input

    list_comprehensions/src/list_comprehensions/__init__.py
    24def 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    ]
    

    the terminal is my friend, and shows TypeError

    terminal
    TypeError: 'bool' object is not callable
    
  • 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

    list_comprehensions/src/list_comprehensions/__init__.py
    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

    list_comprehensions/src/list_comprehensions/__init__.py
    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

    terminal
    git commit -am \
    'add test_making_a_list_w_conditions'
    

Which of the options shown so far do you like? Which is simpler and easier to understand or remember?

I know how to make a list with conditions (filter a list).


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

list_comprehensions/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

terminal
AssertionError: Lists differ: [0, 1, 4, 9, ...]
                           != [0, 1, 2, 3, ...]

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

list_comprehensions/tests/test_list_comprehensions.py
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

    list_comprehensions/tests/test_list_comprehensions.py
    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 seen
    

    the terminal is my friend, and shows AttributeError

    terminal
    AttributeError: module 'src.list_comprehensions'
                    has no attribute 'square'
    
  • I add the function to src/list_comprehensions/__init__.py

    list_comprehensions/src/list_comprehensions/__init__.py
    33    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**y is how to write x raised to the power of y

    \[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 square function with a lambda function

    list_comprehensions/src/list_comprehensions/__init__.py
    39def 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

    terminal
    AssertionError: <map object at 0xffffa1b234c5>
                 != [0, 1, 4, 9, ...]
    

    I have to change the map object to a list.

  • I add the list constructor to the square function

    list_comprehensions/src/list_comprehensions/__init__.py
    39def 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.py

    list_comprehensions/tests/test_list_comprehensions.py
     3import unittest
     4
     5
     6def process(number):
     7    return number ** 2
     8
     9
    10def condition(number):
    
  • I call the new function in the for loop in test_making_a_list_w_processes

    list_comprehensions/tests/test_list_comprehensions.py
    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

    list_comprehensions/tests/test_list_comprehensions.py
    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

    list_comprehensions/tests/test_list_comprehensions.py
     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 seen
    

    green.

  • I remove the commented line

    list_comprehensions/tests/test_list_comprehensions.py
     97        self.assertEqual(
     98            src.list_comprehensions.square(self.an_iterable),
     99            [process(item) for item in self.an_iterable]
    100        )
    101
    102
    103# Exceptions seen
    
  • I add a git commit message

    terminal
    git commit -am \
    'add test_making_a_list_w_processes'
    

    Note

    process is 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

terminal
AssertionError: Lists differ: [0, 4, 16, ...]
                           != [0, 1, 2, 3, 4, ...]

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 condition function

    list_comprehensions/tests/test_list_comprehensions.py
    110        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

    terminal
    AssertionError: Lists differ: [0, 4, 16, 36, ...]
    != [0, 2, 4, 6, ...]
    

    the numbers on the left are squares of the numbers on the right

  • I add a call to the process function, in test_making_a_list_w_processes_and_conditions

    list_comprehensions/tests/test_list_comprehensions.py
    110        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 seen
    

    the test passes.


REFACTOR: make it better


  • I add another assertion

    list_comprehensions/tests/test_list_comprehensions.py
    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 seen
    

    the terminal is my friend, and shows AssertionError

    terminal
    AssertionError: Lists differ: [1, 9, 25, 49, ...]
                               != [0, 1, 2, 3, 4, 5, 6, 7, ...]
    

    the numbers on the left are the squares of the odd numbers from the right.

  • I add a call to the condition function and negate the result

    list_comprehensions/tests/test_list_comprehensions.py
    118        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 seen
    

    the terminal is my friend, and shows AssertionError

    terminal
    AssertionError: Lists differ: [1, 9, 25, 49, ...]
                               != [1, 3, 5, 7, ...]
    

    the numbers on the left are squares of the numbers on the right.

  • I add a call to the process function

    list_comprehensions/tests/test_list_comprehensions.py
    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
    

    the test passes.

  • I add a git commit message

    terminal
    git commit -am \
    'add test_making_a_list_w_processes_and_conditions'
    

I know how to use list comprehensions to make a list based on conditions (filter) with processes (transform).

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.py and src/list_comprehensions/__init__.py

  • I click in the terminal, then use q on the keyboard to leave the tests

  • I change directory to the parent of list_comprehensions

    terminal
    cd ..
    

review

I ran tests to show I can make a list from an iterable with


How many questions can you answer after going through this chapter?


code from the chapter

Do you want to see all the CODE I typed in this chapter?


what is next?

Would you like to test AssertionError with generators?


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.