Operators, Expressions, and Data Manipulation

List, Set, and Dictionary Comprehension

List Comprehension

portfolio = [
    {'name' : 'IBM', 'shares' : 100, 'price' : 91.1},
    {'name' : 'MSFT', 'shares' : 50, 'price' : 45.67},
    {'name' : 'HPE', 'shares' : 75, 'price' : 34.51},
    {'name' : 'CAT', 'shares' : 60, 'price' : 67.89},
    {'name' : 'IBM', 'shares' : 200, 'price' : 95.25},
]

names = [s['name'] for s in portfolio] # ['IBM', 'MSFT', 'HPE', 'CAT', 'IBM']
more100 = [s['name'] for s in portfolio if s['share'] > 100] # ['IBM']
cost = sum(s['shares'] * s['price'] for s in portfolio])
name_shares = [(s['name'], s['shares']) for s in portfolio]

Set Comprehension

names = {s['name'] for s in portfolio}

Dictionary Comprehension

prices = {s['name'] : s['price'] for s in portfolio}

Generator Expression

nums = [1, 2, 3, 4]
squares = (x * x for x in nums)
print(sum(squares)) # 30

squares = (x * x for x in nums)
print(next(squares)) # 1
print(next(squares)) # 4
print(next(squares)) # 9
print(next(squares)) # 16
print(next(squares)) # "StopIteration" Error

List Comprehension vs. Generator Expression

Wiith a list comprehension, Python actually creates a list that contains the resulting data. With a generator expression, Python creates a generator that merely knows how to produce data on demand. In certain application, this can greately improve performance and memroy use. Here is an example:

with open('data.txt') as f:
    lines = (t.strip() for t in f)
    comments = (t for t in lines if t[0] == '#')
    for comment in comments:
        print(comment)

Last updated