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
Generator Expression
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:
Last updated
Was this helpful?