List comprehension

Many lists are created from existing lists, rather then being created from scratch.

Documentation

  1. List Comprehensions in the Python Tutorial
  2. Comprehensions in the Python Python Language Reference
  3. Generator expressions and list comprehensions

Create a copy of a list

import sys

fortunes = [
    "You will meet a tall, dark stranger",
    "It is the hope and dreams we have that make us great",
    "Someone can read your mind",
    "A refreshing change is in your future",
    "You will be graced by the presence of a loved one soon",
    "Sometimes travel to new places leads to great transformtion",
    "Opportunities surround you if you know where to look",
    "The pleasure of what we enjoy is lost by wanting more",
    "Remember, after rain there's always sunshine",
    "Hard work is always appreciated"
]

#Create a copy of the list.

newFortunes = []
for fortune in fortunes:
    newFortunes.append(fortune)

#Two other ways to create a copy of the list:
#newFortunes = fortunes.copy()
#newFortunes = fortunes[:]   #a slice

for newFortune in newFortunes:
    print(newFortune)

sys.exit(0)
You will meet a tall, dark stranger
It is the hope and dreams we have that make us great
Someone can read your mind
A refreshing change is in your future
You will be graced by the presence of a loved one soon
Sometimes travel to new places leads to great transformtion
Opportunities surround you if you know where to look
The pleasure of what we enjoy is lost by wanting more
Remember, after rain there's always sunshine
Hard work is always appreciated

A faster way to create a copy of a list

import sys

fortunes = [
    "You will meet a tall, dark stranger",
    "It is the hope and dreams we have that make us great",
    "Someone can read your mind",
    "A refreshing change is in your future",
    "You will be graced by the presence of a loved one soon",
    "Sometimes travel to new places leads to great transformtion",
    "Opportunities surround you if you know where to look",
    "The pleasure of what we enjoy is lost by wanting more",
    "Remember, after rain there's always sunshine",
    "Hard work is always appreciated"
]

newFortunes = [fortune for fortune in fortunes]   #a list comprehension

for newFortune in newFortunes:
    print(newFortune)

sys.exit(0)
You will meet a tall, dark stranger
It is the hope and dreams we have that make us great
Someone can read your mind
A refreshing change is in your future
You will be graced by the presence of a loved one soon
Sometimes travel to new places leads to great transformtion
Opportunities surround you if you know where to look
The pleasure of what we enjoy is lost by wanting more
Remember, after rain there's always sunshine
Hard work is always appreciated

Create a slightly modified copy of a list

import sys

fortunes = [
    "You will meet a tall, dark stranger",
    "It is the hope and dreams we have that make us great",
    "Someone can read your mind",
    "A refreshing change is in your future",
    "You will be graced by the presence of a loved one soon",
    "Sometimes travel to new places leads to great transformtion",
    "Opportunities surround you if you know where to look",
    "The pleasure of what we enjoy is lost by wanting more",
    "Remember, after rain there's always sunshine",
    "Hard work is always appreciated"
]

#Create a copy of the list.

newFortunes = []
for fortune in fortunes:
    newFortunes.append(fortune + " in bed")

for newFortune in newFortunes:
    print(newFortune)

sys.exit(0)
You will meet a tall, dark stranger in bed
It is the hope and dreams we have that make us great in bed
Someone can read your mind in bed
A refreshing change is in your future in bed
You will be graced by the presence of a loved one soon in bed
Sometimes travel to new places leads to great transformtion in bed
Opportunities surround you if you know where to look in bed
The pleasure of what we enjoy is lost by wanting more in bed
Remember, after rain there's always sunshine in bed
Hard work is always appreciated in bed

A faster way to create a slightly modified copy of a list

import sys

fortunes = [
    "You will meet a tall, dark stranger",
    "It is the hope and dreams we have that make us great",
    "Someone can read your mind",
    "A refreshing change is in your future",
    "You will be graced by the presence of a loved one soon",
    "Sometimes travel to new places leads to great transformtion",
    "Opportunities surround you if you know where to look",
    "The pleasure of what we enjoy is lost by wanting more",
    "Remember, after rain there's always sunshine",
    "Hard work is always appreciated"
]

newFortunes = [fortune + " in bed" for fortune in fortunes]   #a list comprehension

for newFortune in newFortunes:
    print(newFortune)

sys.exit(0)
You will meet a tall, dark stranger in bed
It is the hope and dreams we have that make us great in bed
Someone can read your mind in bed
A refreshing change is in your future in bed
You will be graced by the presence of a loved one soon in bed
Sometimes travel to new places leads to great transformtion in bed
Opportunities surround you if you know where to look in bed
The pleasure of what we enjoy is lost by wanting more in bed
Remember, after rain there's always sunshine in bed
Hard work is always appreciated in bed

Be selective.

The original list contained 10 strings. The new list contains only 4 strings.

import sys

fortunes = [
    "You will meet a tall, dark stranger",
    "It is the hope and dreams we have that make us great",
    "Someone can read your mind",
    "A refreshing change is in your future",
    "You will be graced by the presence of a loved one soon",
    "Sometimes travel to new places leads to great transformtion",
    "Opportunities surround you if you know where to look",
    "The pleasure of what we enjoy is lost by wanting more",
    "Remember, after rain there's always sunshine",
    "Hard work is always appreciated"
]

newFortunes = [fortune + " in bed" for fortune in fortunes if len(fortune) <= 40]

for newFortune in newFortunes:
    print(newFortune)

sys.exit(0)
You will meet a tall, dark stranger in bed
Someone can read your mind in bed
A refreshing change is in your future in bed
Hard work is always appreciated in bed

Things to try

  1. Suppose each string ended with a period:
    fortunes = [
        "You will meet a tall, dark stranger.",
        "It is the hope and dreams we have that make us great.",
        "Someone can read your mind.",
        etc.
    ]
    
    Then we would have had to change
    newFortunes = [fortune + " in bed" for fortune in fortunes]
    
    to one of the following. For the -1 index, see Indexing. fortune[:-1] is the entire fortune except for the last character (the period); fortune[-1] is the last character.
    newFortunes = [fortune[:-1] + " in bed" + fortune[-1] for fortune in fortunes]
    newFortunes = [f"{fortune[:-1]} in bed{fortune[-1]}" for fortune in fortunes]
    
    You will meet a tall, dark stranger in bed.
    It is the hope and dreams we have that make us great in bed.
    Someone can read your mind in bed.
    etc.
    
  2. Make a new list from two existing lists. See also Cartesian product and itertools.product.
    leanings = ["liberal", "moderate", "conservative"]
    parties = ["Democrat", "Republican"]
    
    #persons is a list of 6 strings.
    persons = [leaning + " " + party for leaning in leanings for party in parties]
    
    for person in persons:
        print(person)
    
    liberal Democrat
    liberal Republican
    moderate Democrat
    moderate Republican
    conservative Democrat
    conservative Republican
    
    leanings = ["liberal", "moderate", "conservative"]
    parties = ["Democrat", "Republican"]
    
    #persons is a list of 6 strings.
    persons = [leaning + " " + party for party in parties for leaning in leanings]
    
    for person in persons:
        print(person)
    
    liberal Democrat
    moderate Democrat
    conservative Democrat
    liberal Republican
    moderate Republican
    conservative Republican
    

    This “lists” don’t have to be lists. They can be any iterables, such as a range of integers or a string of characters:

    for heading in [f"{i}{a}." for i in range(1, 4) for a in "abc"]:
        print(heading)
    
    1a.
    1b.
    1c.
    2a.
    2b.
    2c.
    3a.
    3b.
    3c.
    
  3. Make a new list from two existing lists. This time, each item in the new list will be a list. Think of the new list as a two-dimensional list.
    leanings = ["liberal", "moderate", "conservative"]
    parties = ["Democrat", "Republican"]
    
    #rows is a list of 2 items.  Each of these items is a list of 3 strings.
    rows = [[leaning + " " + party for leaning in leanings] for party in parties]
    
    #Two nested loops because we think of rows as two-dimensional.
    for row in rows:
        for column in row:
            print(f"{column:22}", end = "")
        print()
    
    liberal Democrat      moderate Democrat     conservative Democrat
    liberal Republican    moderate Republican   conservative Republican
    
    leanings = ["liberal", "moderate", "conservative"]
    parties = ["Democrat", "Republican"]
    
    #rows is a list of 3 items.  Each of these items is a list of 2 strings.
    rows = [[leaning + " " + party for party in parties] for leaning in leanings ]
    
    #Two nested loops because we think of rows as two-dimensional.
    for row in rows:
        for column in row:
            print(f"{column:22}", end = "")
        print()
    
    liberal Democrat      liberal Republican
    moderate Democrat     moderate Republican
    conservative Democrat conservative Republican
    
  4. A numeric example. All the prices just went up six percent.
    prices = [
             1.00,
        35_000.00,
            29.95,
           300.00,
            19.99
    ]
    
    inflatedPrices = [1.06 * price for price in prices]   #six percent inflation
    
    for inflatedPrice in inflatedPrices:
        print(f"$ {inflatedPrice:9,.2f}")
    
    $      1.06
    $ 37,100.00
    $     31.75
    $    318.00
    $     21.19
    
  5. Add a column to a list. In this case we are changing a one-dimensional list into a two-dimensional list.
    prices = [                                             #a list of 5 floats
             1.00,
        35_000.00,
            29.95,
           300.00,
            19.99
    ]
    
    inflated = [[price, 1.06 * price] for price in prices] #a list of 5 lists
    print(inflated)
    print()
    
    print("original       inflated")
    for row in inflated:
        print(f"${row[0]:9,.2f}     ${row[1]:9,.2f}")
    
    [[1.0, 1.06], [35000.0, 37100.0], [29.95, 31.747], [300.0, 318.0], [19.99, 21.1894]]
    
    original       inflated
    $     1.00     $     1.06
    $35,000.00     $37,100.00
    $    29.95     $    31.75
    $   300.00     $   318.00
    $    19.99     $    21.19
    
  6. Get a column from a two-dimensional list (i.e., from a list of lists).
    pip3 install matplotlib
    
    """
    Pie chart
    
    https://matplotlib.org/3.1.1/gallery/pie_and_polar_charts/pie_features.html
    """
    
    import matplotlib.pyplot
    
    #List of pie slices, counterclockwise from the startangle.
    #The trailing edge (not the center) of the first slice is at the startangle.
    #The four fields are label, color, size (in percent), explode distance from
    #center (in radii).
    
    animals = [
        ["Rabbits",  "red",    15, 0.0],
        ["Cats",     "orange", 30, 0.0],
        ["Dogs",     "yellow", 45, 0.1],
        ["Hamsters", "green",  10, 0.0]
    ]
    
    #Get the four columns with four list comprehensions.
    labels  = [animal[0] for animal in animals]   #Create a list of 4 strings.
    colors  = [animal[1] for animal in animals]   #Create a list of 4 strings.
    sizes   = [animal[2] for animal in animals]   #Create a list of 4 ints.
    explode = [animal[3] for animal in animals]   #Create a list of 4 floats.
    
    figure, axes = matplotlib.pyplot.subplots()
    figure.canvas.set_window_title("Popular Pets")
    axes.axis("equal")   #Equal aspect ratio ensures that circle is not stretched or squished.
    
    axes.pie(
        sizes,
        explode = explode,
        labels = labels,
        colors = colors,
        autopct = "%.1f%%", #autopercent, means f"{percent:.1f}%"
        shadow = True,
        startangle = 90     #degrees clockwise from 3 o'clock
    )
    
    matplotlib.pyplot.show()
    
  7. Discard the resulting list. The return value of print is None.
    prices = [10, 20, 30]
    
    for price in prices:
        print(f"${price:.2f}")
    
    print()
    
    _ = [print(f"${price:.2f}") for price in prices]   #_ is the list [None, None, None]
    
    $10.00
    $20.00
    $30.00
    
    $10.00
    $20.00
    $30.00
    
  8. Delete items from a list by creating a new list in which the items are missing.
    """
    Print the primes from 2 to 100 inclusive using the Sieve of Eratosthenes.
    """
    
    import sys
    
    r = range(2, 101)
    
    while r:
        prime = r[0]
        print(prime)
        r = [i for i in r if i % prime]   #Remove all the multiples of prime from r.
    
    sys.exit(0)
    
    2
    3
    5
    7
    11
    13
    17
    19
    23
    29
    31
    37
    41
    43
    47
    53
    59
    61
    67
    71
    73
    79
    83
    89
    97
    
    """
    Print the primes from 2 to 100.  Test each candidate individually.
    """
    
    import sys
    
    def isprime(n):
        "Return True if n is a prime number."
        listOfFactors = [i for i in range(2, n) if n % i == 0]
        return not listOfFactors   #Return True if listOfFactors is empty.
    
    print([n for n in range(2, 101) if isprime(n)])
    sys.exit(0)
    
    def isprime(n):
        "Return True if n is a prime number."
        return all([n % i for i in range(2, n)])   #Return True if all the numbers in the list are non-zero.
    
  9. Other examples of list comprehensions in this course:
    1. Manhattan address algorithm: list comprehension without an if. Create the new list using every item in the existing list.
    2. CSV: list comprehension with and without an if. The latter creates the new list without using every item in the existing list.
    3. Roman: list comprehension with an if.
    4. Set: list comprehension without an if.
    5. Intersect: list comprehension without an if.
    6. Pandas: with and without an if.
    For a dictionary comprehension, see Variable Keyword.