0% found this document useful (0 votes)
17 views187 pages

Lesson 03

This document provides an overview of data structures in Python, focusing on lists, dictionaries, and tuples. It covers their definitions, methods, and operations, including how to create, access, and manipulate these structures. Additionally, it discusses advanced topics such as nested lists and argument packing/unpacking.

Uploaded by

volinzz3
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
17 views187 pages

Lesson 03

This document provides an overview of data structures in Python, focusing on lists, dictionaries, and tuples. It covers their definitions, methods, and operations, including how to create, access, and manipulate these structures. Additionally, it discusses advanced topics such as nested lists and argument packing/unpacking.

Uploaded by

volinzz3
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 187

Data Structures

Lesson 3
Agenda
Lists
Dictionaries
Tuples
Sets
Advanced Looping
Comprehensions
Lists
Lists

Finite, ordered, mutable


sequence of elements
Lists

easy_as = [1,2,3]
Lists

Square brackets delimit lists

easy_as = [1,2,3]
Lists

Square brackets delimit lists

easy_as = [1,2,3]
Commas separate elements
Basic Lists
Basic Lists
# Create a new list
empty = []
letters = ['a', 'b', 'c', 'd']
numbers = [2, 3, 5]
Basic Lists
# Create a new list
empty = []
letters = ['a', 'b', 'c', 'd']
numbers = [2, 3, 5]

# Lists can contain elements of different types


mixed = [4, 5, "seconds"]
Basic Lists
# Create a new list
empty = []
letters = ['a', 'b', 'c', 'd']
numbers = [2, 3, 5]

# Lists can contain elements of different types


mixed = [4, 5, "seconds"]

# Append elements to the end of a list


numbers.append(7) # numbers == [2, 3, 5, 7]
numbers.append(11) # numbers == [2, 3, 5, 7, 11]
Inspecting List Elements
Inspecting List Elements
# Access elements at a particular index
numbers[0] # => 2
numbers[-1] # => 11
Inspecting List Elements
# Access elements at a particular index
numbers[0] # => 2
numbers[-1] # => 11

# You can also slice lists - the usual rules apply


letters[:3] # => ['a', 'b', 'c']
numbers[1:-1] # => [3, 5, 7]
Nested Lists
Nested Lists
# Lists really can contain anything - even other lists!
x = [letters, numbers]
x # => [['a', 'b', 'c', 'd'], [2, 3, 5, 7, 11]]
Nested Lists
# Lists really can contain anything - even other lists!
x = [letters, numbers]
x # => [['a', 'b', 'c', 'd'], [2, 3, 5, 7, 11]]
x[0] # => ['a', 'b', 'c', 'd']
Nested Lists
# Lists really can contain anything - even other lists!
x = [letters, numbers]
x # => [['a', 'b', 'c', 'd'], [2, 3, 5, 7, 11]]
x[0] # => ['a', 'b', 'c', 'd']
x[0][1] # => 'b'
Nested Lists
# Lists really can contain anything - even other lists!
x = [letters, numbers]
x # => [['a', 'b', 'c', 'd'], [2, 3, 5, 7, 11]]
x[0] # => ['a', 'b', 'c', 'd']
x[0][1] # => 'b'
x[1][2:] # => [5, 7, 11]
List Method Reference
List Method Reference
# Extend list by appending elements from the iterable
my_list.extend(iterable)
List Method Reference
# Extend list by appending elements from the iterable
my_list.extend(iterable)

# Insert object before index


my_list.insert(index, object)
List Method Reference
# Extend list by appending elements from the iterable
my_list.extend(iterable)

# Insert object before index


my_list.insert(index, object)

# Remove first occurrence of value, or raise ValueError


my_list.remove(value)
List Method Reference
# Extend list by appending elements from the iterable
my_list.extend(iterable)

# Insert object before index


my_list.insert(index, object)

# Remove first occurrence of value, or raise ValueError


my_list.remove(value)

# Remove all items


my_list.clear()
More List Methods
More List Methods
# Return number of occurrences of value
my_list.count(value)
More List Methods
# Return number of occurrences of value
my_list.count(value)

# Return first index of value, or raise ValueError


my_list.index(value, [start, [stop]])
More List Methods
# Return number of occurrences of value
my_list.count(value)

# Return first index of value, or raise ValueError


my_list.index(value, [start, [stop]])

# Remove, return item at index (def. last) or IndexError


my_list.pop([index])
More List Methods
# Return number of occurrences of value
my_list.count(value)

# Return first index of value, or raise ValueError


my_list.index(value, [start, [stop]])

# Remove, return item at index (def. last) or IndexError


my_list.pop([index])

# Stable sort *in place*


my_list.sort(key=None, reverse=False)
More List Methods
# Return number of occurrences of value
my_list.count(value)

# Return first index of value, or raise ValueError


my_list.index(value, [start, [stop]])

# Remove, return item at index (def. last) or IndexError


my_list.pop([index])

# Stable sort *in place*


my_list.sort(key=None, reverse=False)

# Reverse *in place*.


my_list.reverse()
General Queries on Iterables
General Queries on Iterables
# Length (len)
len([]) # => 0
len("python") # => 6
len([4,5,"seconds"]) # => 3
General Queries on Iterables
# Length (len)
len([]) # => 0
len("python") # => 6
len([4,5,"seconds"]) # => 3

# Membership (in)
0 in [] # => False
'y' in 'python' # => True
'minutes' in [4, 5, 'seconds'] # => False
Dictionaries
Dictionary

Mutable map from hashable


values to arbitrary objects
Dictionary
Keys can be a variety of types,
as long as they are hashable

Mutable map from hashable


values to arbitrary objects
Dictionary
Keys can be a variety of types,
as long as they are hashable

Mutable map from hashable


values to arbitrary objects
Values can be a variety of types too
Create a Dictionary
Create a Dictionary
empty = {}
type(empty) # => dict
empty == dict() # => True
Create a Dictionary
empty = {}
type(empty) # => dict
empty == dict() # => True

a = dict(one=1, two=2, three=3)


b = {"one": 1, "two": 2, "three": 3}
a == b # => True
Access and Mutate
Access and Mutate
b = {"one": 1, "two": 2, "three": 3}
Access and Mutate
b = {"one": 1, "two": 2, "three": 3}

# Get
d['one'] # => 1
d['five'] # raises KeyError
Access and Mutate
b = {"one": 1, "two": 2, "three": 3}

# Get
d['one'] # => 1
d['five'] # raises KeyError

# Set
d['two'] = 22 # Modify an existing key
d['four'] = 4 # Add a new key
Get with Default
Get with Default
d = {"CS":[106, 107, 110], "MATH": [51, 113]}
Get with Default
d = {"CS":[106, 107, 110], "MATH": [51, 113]}
d["COMPSCI"] # raises KeyError
Get with Default
d = {"CS":[106, 107, 110], "MATH": [51, 113]}
d["COMPSCI"] # raises KeyError
Use get() method to avoid the KeyError
d.get("CS") # => [106, 107, 110]
d.get("PHIL") # => None (not a KeyError!)
Get with Default
d = {"CS":[106, 107, 110], "MATH": [51, 113]}
d["COMPSCI"] # raises KeyError
Use get() method to avoid the KeyError
d.get("CS") # => [106, 107, 110]
d.get("PHIL") # => None (not a KeyError!)

english_classes = d.get("ENGLISH", [])


num_english = len(english_classes)

Works even if there were no English classes in our dictionary!


Delete
Delete
d = {"one": 1, "two": 2, "three": 3}
Delete
d = {"one": 1, "two": 2, "three": 3}

del d["one"] Raises KeyError if invalid key


Delete
d = {"one": 1, "two": 2, "three": 3}

del d["one"] Raises KeyError if invalid key

Remove and return d['three']


d.pop("three", default) # => 3
or default value if not in the map
Delete
d = {"one": 1, "two": 2, "three": 3}

del d["one"] Raises KeyError if invalid key

Remove and return d['three']


d.pop("three", default) # => 3
or default value if not in the map

(key, value) pair.


d.popitem() # => ("two", 2)
Useful for destructive iteration
Dictionaries
Dictionaries
d = {"one": 1, "two": 2, "three": 3}
Dictionaries
d = {"one": 1, "two": 2, "three": 3}
d.keys()
d.values()
d.items()
Dictionaries
d = {"one": 1, "two": 2, "three": 3}
d.keys()
These dictionary views are dynamic,
d.values()
reflecting changes in the underlying dictionary!
d.items()
Dictionaries
d = {"one": 1, "two": 2, "three": 3}
d.keys()
These dictionary views are dynamic,
d.values()
reflecting changes in the underlying dictionary!
d.items()
len(d.keys()) # => 3
Dictionaries
d = {"one": 1, "two": 2, "three": 3}
d.keys()
These dictionary views are dynamic,
d.values()
reflecting changes in the underlying dictionary!
d.items()
len(d.keys()) # => 3
('one', 1) in d.items()
Dictionaries
d = {"one": 1, "two": 2, "three": 3}
d.keys()
These dictionary views are dynamic,
d.values()
reflecting changes in the underlying dictionary!
d.items()
len(d.keys()) # => 3
('one', 1) in d.items()
for value in d.values():
print(value)
Dictionaries
d = {"one": 1, "two": 2, "three": 3}
d.keys()
These dictionary views are dynamic,
d.values()
reflecting changes in the underlying dictionary!
d.items()
len(d.keys()) # => 3
('one', 1) in d.items()
for value in d.values():
print(value)
keys_list = list(d.keys())
Dictionaries
d = {"one": 1, "two": 2, "three": 3}
d.keys()
These dictionary views are dynamic,
d.values()
reflecting changes in the underlying dictionary!
d.items()
len(d.keys()) # => 3 KeysView

('one', 1) in d.items()
MappingView ValuesView
for value in d.values():
len(view)
print(value) iter(view) ItemsView
x in view
keys_list = list(d.keys())
Common Dict Operations
Common Dict Operations
len(d)
Common Dict Operations
len(d)
key in d # equiv. to `key in d.keys()`
Common Dict Operations
len(d)
key in d # equiv. to `key in d.keys()`
value in d.values()
Common Dict Operations
len(d)
key in d # equiv. to `key in d.keys()`
value in d.values()
d.copy()
Common Dict Operations
len(d)
key in d # equiv. to `key in d.keys()`
value in d.values()
d.copy()
d.clear()
Common Dict Operations
len(d)
key in d # equiv. to `key in d.keys()`
value in d.values()
d.copy()
d.clear()
for key in d: # equiv. to `for key in d.keys():`
print(key)
Tuples
Tuple

Immutable Sequences
Tuple

t = (1, "cat")
Tuple

Tuples are delimited by parentheses

t = (1, "cat")
Tuple

Tuples are delimited by parentheses

t = (1, "cat")
Elements are separated by commas
Primary Motivations
Primary Motivations

Store collections of heterogeneous data


Primary Motivations

Store collections of heterogeneous data

"Freeze" sequence to ensure hashability


Tuples can be dictionary keys, but lists cannot
Primary Motivations

Store collections of heterogeneous data

"Freeze" sequence to ensure hashability


Tuples can be dictionary keys, but lists cannot

Enforce immutability for fixed-size collections


Tuples
Tuples
fish = (1, 2, "red", "blue")
Tuples
fish = (1, 2, "red", "blue")
fish[0] # => 1
Tuples
fish = (1, 2, "red", "blue")
You can't change any
fish[0] # => 1
elements in a tuple!
fish[0] = 7 # Raises a TypeError
Tuples
fish = (1, 2, "red", "blue")
You can't change any
fish[0] # => 1
elements in a tuple!
fish[0] = 7 # Raises a TypeError

len(fish) # => 4
fish[:2] # => (1, 2) Although the usual sequence
"red" in fish # => True methods still work
Argument Packing and Unpacking
Argument Packing and Unpacking
t = 12345, 54321, 'hello!'
Argument Packing and Unpacking
t = 12345, 54321, 'hello!'
Comma-separated Rvalues
are converted to a tuple
Argument Packing and Unpacking
t = 12345, 54321, 'hello!'
Comma-separated Rvalues
print(t) # (12345, 54321, 'hello!')
are converted to a tuple
type(t) # => tuple
Argument Packing and Unpacking
t = 12345, 54321, 'hello!'
Comma-separated Rvalues
print(t) # (12345, 54321, 'hello!')
are converted to a tuple
type(t) # => tuple

x, y, z = t
Argument Packing and Unpacking
t = 12345, 54321, 'hello!'
Comma-separated Rvalues
print(t) # (12345, 54321, 'hello!')
are converted to a tuple
type(t) # => tuple

x, y, z = t
Comma-separated Lvalues
are unpacked automatically
Argument Packing and Unpacking
t = 12345, 54321, 'hello!'
Comma-separated Rvalues
print(t) # (12345, 54321, 'hello!')
are converted to a tuple
type(t) # => tuple

x, y, z = t
x # => 12345 Comma-separated Lvalues
y # => 54321 are unpacked automatically
z # => 'hello!'
Swapping Values
x=5 x=6
Have Want
y=6 y=5
Swapping Values
x=5 x=6
Have Want
y=6 y=5
temp = x
x=y
y = temp

print(x, y)
# => 6 5

Temporary
Variable
Swapping Values
x=5 x=6
Have Want
y=6 y=5
temp = x x=x^y
x=y y=x^y
y = temp x=x^y

print(x, y) print(x, y)
# => 6 5 # => 6 5

Temporary XOR
Variable Magic
Swapping Values
x=5 x=6
Have Want
y=6 y=5
temp = x x=x^y x, y = y, x
x=y y=x^y
y = temp x=x^y

print(x, y) print(x, y) print(x, y)


# => 6 5 # => 6 5 # => 6 5

Temporary XOR
Variable Magic Tuple Packing
Swapping Values
x=5 x=6
Have Want
y=6 y=5

x, y = y, x
Swapping Values
x=5 x=6
Have Want
y=6 y=5

First, y, x is packed into the tuple (6, 5)

x, y = y, x
Swapping Values
x=5 x=6
Have Want
y=6 y=5

First, y, x is packed into the tuple (6, 5)

x, y = y, x
Then, (6, 5) is unpacked into the variables x and y respectively
Tuple example: Fibonacci Sequence
Tuple example: Fibonacci Sequence
def fib(n):
"""Prints the first n Fibonacci numbers."""
Tuple example: Fibonacci Sequence
def fib(n):
"""Prints the first n Fibonacci numbers."""
a, b = 0, 1
Tuple example: Fibonacci Sequence
def fib(n):
"""Prints the first n Fibonacci numbers."""
a, b = 0, 1
for i in range(n):
print(i, a)
Tuple example: Fibonacci Sequence
def fib(n):
"""Prints the first n Fibonacci numbers."""
a, b = 0, 1
for i in range(n):
print(i, a)
a, b = b, a + b
Tuple example: enumerate
Tuple example: enumerate
for index, color in enumerate(['red','green','blue']):
print(index, color)
Tuple example: enumerate
for index, color in enumerate(['red','green','blue']):
print(index, color)

# =>
# 0 red
# 1 green
# 2 blue
Tuple example: enumerate
for index, color in enumerate(['red','green','blue']):
print(index, color)

# =>
# 0 red
# 1 green
# 2 blue

This also means you should almost never use


for i in range(len(sequence)):
Quirks
Quirks
empty = ()
singleton = ("value",) # pay attention to the ‘,’
plain_string = "value" # Note plain_string != singleton
Quirks
empty = ()
singleton = ("value",) # pay attention to the ‘,’
plain_string = "value" # Note plain_string != singleton
len(empty) # => 0
len(singleton) # => 1
Quirks
empty = ()
singleton = ("value",) # pay attention to the ‘,’
plain_string = "value" # Note plain_string != singleton
len(empty) # => 0
len(singleton) # => 1

v = ([1, 2, 3], ['a', 'b', 'c'])


Quirks
empty = ()
singleton = ("value",) # pay attention to the ‘,’
plain_string = "value" # Note plain_string != singleton
len(empty) # => 0
len(singleton) # => 1

v = ([1, 2, 3], ['a', 'b', 'c'])


v[0].append(4)
Quirks
empty = ()
singleton = ("value",) # pay attention to the ‘,’
plain_string = "value" # Note plain_string != singleton
len(empty) # => 0
len(singleton) # => 1

v = ([1, 2, 3], ['a', 'b', 'c'])


v[0].append(4)
v # => ([1, 2, 3, 4], ['a', 'b', 'c'])
Quirks
empty = ()
singleton = ("value",) # pay attention to the ‘,’
plain_string = "value" # Note plain_string != singleton
len(empty) # => 0
len(singleton) # => 1
Tuples contain (immutable)
references to underlying objects!
v = ([1, 2, 3], ['a', 'b', 'c'])
v[0].append(4)
v # => ([1, 2, 3, 4], ['a', 'b', 'c'])
Sets
Set

Unordered collection of
distinct hashable elements
Primary Motivations
Primary Motivations

Fast membership testing


O(1) vs. O(n)
Primary Motivations

Fast membership testing


O(1) vs. O(n)
Eliminate duplicate entries
Primary Motivations

Fast membership testing


O(1) vs. O(n)
Eliminate duplicate entries
Easy set operations (intersection, union, etc.)
Set

s = {1, 3, 4}
Unordered collection of distinct hashable elements
Set

Sets are delimited by curly braces

s = {1, 3, 4}
Unordered collection of distinct hashable elements
Set

Sets are delimited by curly braces

s = {1, 3, 4}
Elements are separated by commas

Unordered collection of distinct hashable elements


Common Set Operations
Common Set Operations
empty_set = set() # Why not {} ?
Common Set Operations
empty_set = set()
set_from_list = set([1, 2, 1, 4, 3]) # => {1, 3, 4, 2}
Common Set Operations
empty_set = set()
set_from_list = set([1, 2, 1, 4, 3]) # => {1, 3, 4, 2}

basket = {"apple", "orange", "apple", "pear", "banana"}


Common Set Operations
empty_set = set()
set_from_list = set([1, 2, 1, 4, 3]) # => {1, 3, 4, 2}

basket = {"apple", "orange", "apple", "pear", "banana"}


len(basket) # => 4
Common Set Operations
empty_set = set()
set_from_list = set([1, 2, 1, 4, 3]) # => {1, 3, 4, 2}

basket = {"apple", "orange", "apple", "pear", "banana"}


len(basket) # => 4
"orange" in basket # => True
"crabgrass" in basket # => False O(1) membership testing
Common Set Operations
empty_set = set()
set_from_list = set([1, 2, 1, 4, 3]) # => {1, 3, 4, 2}

basket = {"apple", "orange", "apple", "pear", "banana"}


len(basket) # => 4
"orange" in basket # => True
"crabgrass" in basket # => False O(1) membership testing

for fruit in basket:


print(fruit, end='/')
# => pear/banana/apple/orange/
Common Set Operations
Common Set Operations
a = set("mississippi") # {'i', 'm', 'p', 's'}
Common Set Operations
a = set("mississippi") # {'i', 'm', 'p', 's'}

a.add('r')
a.remove('m') # raises KeyError if 'm' is not present
a.discard('x') # same as remove, except no error
Common Set Operations
a = set("mississippi") # {'i', 'm', 'p', 's'}

a.add('r')
a.remove('m') # raises KeyError if 'm' is not present
a.discard('x') # same as remove, except no error

a.pop() # => 's' (or 'i' or 'p')


a.clear()
Common Set Operations
a = set("mississippi") # {'i', 'm', 'p', 's'}

a.add('r')
a.remove('m') # raises KeyError if 'm' is not present
a.discard('x') # same as remove, except no error

a.pop() # => 's' (or 'i' or 'p')


a.clear()
len(a) # => 0
Common Set Operations
Common Set Operations
a = set("abracadabra") # {'a', 'r', 'b', 'c', 'd'}
b = set("alacazam") # {'a', 'm', 'c', 'l', 'z'}
Common Set Operations
a = set("abracadabra") # {'a', 'r', 'b', 'c', 'd'}
b = set("alacazam") # {'a', 'm', 'c', 'l', 'z'}

# Set difference
a - b # => {'r', 'd', 'b'}
Common Set Operations
a = set("abracadabra") # {'a', 'r', 'b', 'c', 'd'}
b = set("alacazam") # {'a', 'm', 'c', 'l', 'z'}

# Set difference
a - b # => {'r', 'd', 'b'}

# Union
a | b # => {'a', 'c', 'r', 'd', 'b', 'm', 'z', 'l'}
Common Set Operations
a = set("abracadabra") # {'a', 'r', 'b', 'c', 'd'}
b = set("alacazam") # {'a', 'm', 'c', 'l', 'z'}

# Set difference
a - b # => {'r', 'd', 'b'}

# Union
a | b # => {'a', 'c', 'r', 'd', 'b', 'm', 'z', 'l'}

# Intersection
a & b # => {'a', 'c'}
Common Set Operations
a = set("abracadabra") # {'a', 'r', 'b', 'c', 'd'}
b = set("alacazam") # {'a', 'm', 'c', 'l', 'z'}

# Set difference
a - b # => {'r', 'd', 'b'}

# Union
a | b # => {'a', 'c', 'r', 'd', 'b', 'm', 'z', 'l'}

# Intersection
a & b # => {'a', 'c'}

# Symmetric Difference
a ^ b # => {'r', 'd', 'b', 'm', 'z', 'l'}
Looping Techniques
Items in Dictionary
Items in Dictionary
knights = {'gallahad': 'the pure', 'robin': 'the brave'}
Items in Dictionary
knights = {'gallahad': 'the pure', 'robin': 'the brave'}
for k, v in knights.items():
print(k, v)
Items in Dictionary
knights = {'gallahad': 'the pure', 'robin': 'the brave'}
for k, v in knights.items():
print(k, v)

# =>
# gallahad the pure
# robin the brave
zip
zip
questions = ['name', 'quest', 'favorite color']
answers = ['Lancelot', 'To seek the holy grail', 'Blue']
zip
questions = ['name', 'quest', 'favorite color']
answers = ['Lancelot', 'To seek the holy grail', 'Blue']
for q, a in zip(questions, answers):
print('What is your {0}? {1}.'.format(q, a))
zip
questions = ['name', 'quest', 'favorite color']
answers = ['Lancelot', 'To seek the holy grail', 'Blue']
for q, a in zip(questions, answers):
print('What is your {0}? {1}.'.format(q, a))
The zip() function generates pairs of entries
from its arguments.
zip
questions = ['name', 'quest', 'favorite color']
answers = ['Lancelot', 'To seek the holy grail', 'Blue']
for q, a in zip(questions, answers):
print('What is your {0}? {1}.'.format(q, a))
The zip() function generates pairs of entries
# => from its arguments.
# What is your name? Lancelot.
# What is your quest? To seek the holy grail.
# What is your favorite color? Blue.
Reverse Iteration
Reverse Iteration
for i in reversed(range(1, 10, 2)):
print(i, end=', ')
Reverse Iteration
for i in reversed(range(1, 10, 2)):
print(i, end=', ')

# =>
# 9, 7, 5, 3, 1,
Reverse Iteration
for i in reversed(range(1, 10, 2)):
print(i, end=', ')

# =>
# 9, 7, 5, 3, 1,

To loop over a sequence in reverse,


first specify the sequence in a forward direction
and then call the reversed() function.
Sorted Iteration
Sorted Iteration
basket = ['pear', 'banana', 'orange', 'pear', 'apple']
Sorted Iteration
basket = ['pear', 'banana', 'orange', 'pear', 'apple']
for fruit in sorted(basket):
print(fruit)
Sorted Iteration
basket = ['pear', 'banana', 'orange', 'pear', 'apple']
for fruit in sorted(basket):
print(fruit)
# =>
# apple
# banana
# orange
# pear
# pear
Sorted Iteration
basket = ['pear', 'banana', 'orange', 'pear', 'apple']
for fruit in sorted(basket):
print(fruit)
# =>
# apple
# banana
# orange
# pear To loop over a sequence in sorted order,
# pear use the sorted() function which returns
a new sorted list while leaving the source unaltered.
Comprehensions
Concise syntax for creating
data structures
Comprehensions
Comprehensions

squares = [ ]
Comprehensions

squares = [ ]
for x in range(10):
Comprehensions

squares = [ ]
for x in range(10):
squares.append(x**2)
Comprehensions

squares = [ ]
for x in range(10):
squares.append(x**2)

print(squares)
# [0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
Comprehensions

squares =
Comprehensions

squares = [ ]

Collect in a list
Comprehensions

squares = [ x**2 ]

Collect in a list
the x**2 values
Comprehensions

squares = [ x**2 for x in ]

Collect in a list
the x**2 values
for each x in
Comprehensions

squares = [ x**2 for x in range(10) ]

Collect in a list
the x**2 values
for each x in
the range [0,1,…,9]
Comprehensions

[f(xs) for xs in iter]


Comprehensions

Square brackets indicate that we're building a list

[f(xs) for xs in iter]


Comprehensions

Square brackets indicate that we're building a list

Loop over the specified iterable

[f(xs) for xs in iter]


Comprehensions

Square brackets indicate that we're building a list

Loop over the specified iterable

[f(xs) for xs in iter]


Apply some operation to
the loop variable(s) to generate
new list elements
Comprehensions

Square brackets indicate that we're building a list

Loop over the specified iterable

[f(xs) for xs in iter if pred(xs)]


Apply some operation to Only keep elements that
the loop variable(s) to generate satisfy a predicate condition
new list elements
Examples of List Comprehensions
Examples of List Comprehensions
[word.lower() for word in sentence]
Examples of List Comprehensions
[word.lower() for word in sentence]
[word for word in sentence if len(word) > 8]
Examples of List Comprehensions
[word.lower() for word in sentence]
[word for word in sentence if len(word) > 8]

[(x, x ** 2, x ** 3) for x in range(10)]


Examples of List Comprehensions
[word.lower() for word in sentence]
[word for word in sentence if len(word) > 8]

[(x, x ** 2, x ** 3) for x in range(10)]


[(i,j) for i in range(5) for j in range(i)]
Other Comprehensions
Other Comprehensions
# Dictionary Comprehensions
{key_func(vars):val_func(vars) for vars in iterable}
Other Comprehensions
# Dictionary Comprehensions
{key_func(vars):val_func(vars) for vars in iterable}
{v:k for k, v in d.items()}
Other Comprehensions
# Dictionary Comprehensions
{key_func(vars):val_func(vars) for vars in iterable}
{v:k for k, v in d.items()}

# Set Comprehensions
{func(vars) for vars in iterable}
Other Comprehensions
# Dictionary Comprehensions
{key_func(vars):val_func(vars) for vars in iterable}
{v:k for k, v in d.items()}

# Set Comprehensions
{func(vars) for vars in iterable}
{word for word in hamlet if is_palindrome(word.lower())}

You might also like