List Comprehensions

Objective

Students will use list comprehensions in place of simple for loops to create new lists.

Homework Content

  1. Lets Create a List:

    x = [1, 2, 3]
    
  2. Lets loop over the list and create a new value for each item in the list:

    for item in x:
        print(item + 1)
    
  3. Here’s how we could add each item to a new list that we can reuse somewhere else:

    newx = [ ]
    for item in x:
        newx.append(item + 1)
    
    print(x)
    print(newx)
    
  4. Here’s a list comprehension (aka list comp), it is short hand for the syntax we used above to create the new list. It is much shorter and just as easy to read if you are familiar with the list comp syntax.:

    del newx
    newx = [item for item in x if item > 1]
    print(newx)
    

Problems

bills = [(192, 'paid', 0),
        (331, 'due', 1),
        (515, 'paid', 2),
        (135, 'due', 3)
        ]
nums = [2,3,4,7,16]
  1. Replace the following with a list comprehension:

    squared = [ ]
    
    for num in nums:
        squared.append(num**2)
    
  2. Replace the following with a list comprehension:

    squared  = [ ]
    
    for num in nums:
        if num % 2 == 0:
            square.append(num**2)
    
  3. Replace the following with a list comprehension for Sales greater than $150:

    sales = []
    
    for bill in bills:
        if bill[0] > 150:
            sales.append(bill)
    
  4. Replace the following with a list comprehension for Bills due greater than $150:

    due = []
    
    for bill in bills:
        if bill[0] > 150 and bill[1] == 'due':
            due.append(bill)
    
  5. Replace the following with a list comprehension:

    results = []
    
    for bill in bills:
        for num in nums:
            if bill[2] == num:
                results.append((bill, num))
    

Metadata

Title:List_comprehension
CreationDate:12/16/2013
SoftwareUsed:None
SoftwareVersion: None
Contributors: Zac Miller, Crystal Lyliston