3. Set Comprehensions
See ref video at: https://www.youtube.com/watch?v=1bwCstN0pFs
3.1. Set comprehension without condition
set()
.{ }
, since that creates an empty dictionary instead.Syntax:
- new_set = {expression for item in iterable}
- Parameters:
expression – the item variable only (e.g. x) or any expression such as one that uses the item variable (e.g. x * x).
item – a variable.
iterable – iterable objects like strings, lists, dictionaries, range function and others.
{ }
containing an expression followed by a for clause.nums = [1, 2, 3, 1, 2, 3]
my_set_comprehension = {n for n in nums}
print(my_set_comprehension)
str_nums = ['2', '2', '3', '3', '3', '6', '6', '7', '7', '8']
num_set = {int(num) for num in str_nums}
print(num_set)
names = ['tom', 'ted', 'tony', 'TOM', 'TONY']
names_set = {n.capitalize() for n in names}
print(names_set)
xy
will get each of the nested lists in tern starting with [1, 2]
.xy[1]
gets the second number. eg. 4
from [1, 4]
.xycoords = [[1, 4], [2, 2], [3, 0], [4, 2]]
y_set = {xy[1] for xy in xycoords}
print(y_set)
nums = [[1, 2], [2, 3], [3, 4], [4, 5]]
flat_set = {a for pair in nums for a in pair}
print(flat_set)
3.1.1. Practice Questions
Tasks
Use a set comprehension with the range function to create {7, 8, 9}.
Use a set comprehension with the range function to create {2, 4, 6, 8}.
3.2. Set comprehension with condition
Syntax:
- new_set = {expression for item in iterable if condition}
- Parameters:
expression – the item variable only (e.g. x) or any expression such as one that uses the item variable (e.g. x * x).
item – a variable.
iterable – iterable objects like strings, lists, dictionaries, range function and others.
condition – any condition.
i % 2 == 0
check to see if the remainder from dividing by is 0.evens = {i for i in range(10) if i % 2 == 0}
print(evens)
nums = [[1,3],[2,3],[3,98],[76,1]] flat_set = {a for b in nums for a in b} print(flat_set) Eliminate Dups from a List
Get Car Make from list of Make & Model We’re getting the first word from each string.
cars = [‘Toyota Prius’, ‘Chevy Bolt’, ‘Tesla Model 3’, ‘Tesla Model Y’] makes = {(c.split()[0]) for c in cars} print(makes) Get Initials from Names Take first and last initials
names = [‘Clint Barton’, ‘Tony’, ‘Nick Fury’, ‘Hank Pym’] inits = {(n.split()[0][0] + n.split()[1][0]) for n in names if len(n.split())==2} print(inits)