In [125]:
# create an empty dictionary (two ways)
empty_dict = {}
empty_dict = dict()
In [126]:
# create a dictionary (two ways)
family = {'dad':'homer', 'mom':'marge', 'size':6}
family = dict(dad='homer', mom='marge', size=6)
family
Out[126]:
In [127]:
# convert a list of tuples into a dictionary
list_of_tuples = [('dad', 'homer'), ('mom', 'marge'), ('size', 6)]
family = dict(list_of_tuples)
family
Out[127]:
In [128]:
# pass a key to return its value
family['dad']
Out[128]:
In [129]:
# return the number of key-value pairs
len(family)
Out[129]:
In [130]:
# check if key exists in dictionary
'mom' in family
Out[130]:
In [131]:
# dictionary values are not checked
'marge' in family
Out[131]:
In [132]:
# returns a list of keys (Python 2) or an iterable view (Python 3)
family.keys()
Out[132]:
In [133]:
# returns a list of values (Python 2) or an iterable view (Python 3)
family.values()
Out[133]:
In [134]:
# returns a list of key-value pairs (Python 2) or an iterable view (Python 3)
family.items()
Out[134]:
In [135]:
# add a new entry
family['cat'] = 'snowball'
family
Out[135]:
In [136]:
# edit an existing entry
family['cat'] = 'snowball ii'
family
Out[136]:
In [137]:
# delete an entry
del family['cat']
family
Out[137]:
In [138]:
# dictionary value can be a list
family['kids'] = ['bart', 'lisa']
family
Out[138]:
In [139]:
# remove an entry and return the value
family.pop('dad')
Out[139]:
In [140]:
# add multiple entries
family.update({'baby':'maggie', 'grandpa':'abe'})
family
Out[140]:
In [141]:
family['mom']
Out[141]:
In [142]:
# equivalent to a dictionary lookup
family.get('mom')
Out[142]:
In [143]:
# this would throw an error since the key does not exist
# family['grandma']
In [144]:
# return None if not found
family.get('grandma')
In [145]:
# provide a default return value if not found
family.get('grandma', 'not found')
Out[145]:
In [146]:
family['kids'][0]
Out[146]:
In [147]:
family['kids'].remove('lisa')
family
Out[147]:
In [148]:
'youngest child is %(baby)s' % family
Out[148]:
In [149]:
# create an empty set
empty_set = set()
In [150]:
# create a set directly
languages = {'python', 'r', 'java'}
In [151]:
# create a set from a list
snakes = set(['cobra', 'viper', 'python'])
In [152]:
len(languages)
Out[152]:
In [153]:
'python' in languages
Out[153]:
In [154]:
# intersection
languages & snakes
Out[154]:
In [155]:
# union
languages | snakes
Out[155]:
In [156]:
# set difference
languages - snakes
Out[156]:
In [157]:
# set difference
snakes - languages
Out[157]:
In [158]:
# add a new element
languages.add('sql')
languages
Out[158]:
In [159]:
# try to add an existing element (ignored, no error)
languages.add('r')
languages
Out[159]:
In [160]:
# remove an element
languages.remove('java')
languages
Out[160]:
In [161]:
# try to remove a non-existing element (this would throw an error)
# languages.remove('c')
In [162]:
# remove an element if present, but ignored otherwise
languages.discard('c')
languages
Out[162]:
In [163]:
# remove and return an arbitrary element
languages.pop()
Out[163]:
In [164]:
# remove all elements
languages.clear()
languages
Out[164]:
In [165]:
# add multiple elements (can also pass a set)
languages.update(['go', 'spark'])
languages
Out[165]:
In [166]:
sorted(set([9, 0, 2, 1, 0]))
Out[166]:
In [167]:
def print_text():
print('this is text')
In [168]:
# call the function
print_text()
In [169]:
def print_this(x):
print(x)
In [170]:
# call the function
print_this(3)
In [171]:
# prints 3, but doesn't assign 3 to n because the function has no return statement
n = print_this(3)
In [172]:
def square_this(x):
return x**2
In [173]:
# include an optional docstring to describe the effect of a function
def square_this(x):
"""Return the square of a number."""
return x**2
In [174]:
# call the function
square_this(3)
Out[174]:
In [175]:
# assigns 9 to var, but does not print 9
var = square_this(3)
In [176]:
def calc(a, b, op='add'):
if op == 'add':
return a + b
elif op == 'sub':
return a - b
else:
print('valid operations are add and sub')
In [177]:
# call the function
calc(10, 4, op='add')
Out[177]:
In [178]:
# unnamed arguments are inferred by position
calc(10, 4, 'add')
Out[178]:
In [179]:
# default for 'op' is 'add'
calc(10, 4)
Out[179]:
In [180]:
calc(10, 4, 'sub')
Out[180]:
In [181]:
calc(10, 4, 'div')
In [182]:
def stub():
pass
In [183]:
def min_max(nums):
return min(nums), max(nums)
In [184]:
# return values can be assigned to a single variable as a tuple
nums = [1, 2, 3]
min_max_num = min_max(nums)
min_max_num
Out[184]:
In [185]:
# return values can be assigned into multiple variables using tuple unpacking
min_num, max_num = min_max(nums)
print(min_num)
print(max_num)
In [186]:
# define a function the "usual" way
def squared(x):
return x**2
In [187]:
# define an identical function using lambda
squared = lambda x: x**2
In [188]:
# without using lambda
simpsons = ['homer', 'marge', 'bart']
def last_letter(word):
return word[-1]
sorted(simpsons, key=last_letter)
Out[188]:
In [189]:
# using lambda
sorted(simpsons, key=lambda word: word[-1])
Out[189]:
In [190]:
# includes the start value but excludes the stop value
range(0, 3)
Out[190]:
In [191]:
# default start value is 0
range(3)
Out[191]:
In [192]:
# third argument is the step value
range(0, 5, 2)
Out[192]:
In [193]:
# Python 2 only: use xrange to create a sequence rather than a list (saves memory)
xrange(100, 100000, 5)
Out[193]:
In [194]:
# not the recommended style
fruits = ['apple', 'banana', 'cherry']
for i in range(len(fruits)):
print(fruits[i].upper())
In [195]:
# recommended style
for fruit in fruits:
print(fruit.upper())
In [196]:
# iterate through two things at once (using tuple unpacking)
family = {'dad':'homer', 'mom':'marge', 'size':6}
for key, value in family.items():
print(key, value)
In [197]:
# use enumerate if you need to access the index value within the loop
for index, fruit in enumerate(fruits):
print(index, fruit)
In [198]:
for fruit in fruits:
if fruit == 'banana':
print('Found the banana!')
break # exit the loop and skip the 'else' block
else:
# this block executes ONLY if the for loop completes without hitting 'break'
print("Can't find the banana")
In [199]:
count = 0
while count < 5:
print('This will print 5 times')
count += 1 # equivalent to 'count = count + 1'
In [200]:
# for loop to create a list of cubes
nums = [1, 2, 3, 4, 5]
cubes = []
for num in nums:
cubes.append(num**3)
cubes
Out[200]:
In [201]:
# equivalent list comprehension
cubes = [num**3 for num in nums]
cubes
Out[201]:
In [202]:
# for loop to create a list of cubes of even numbers
cubes_of_even = []
for num in nums:
if num % 2 == 0:
cubes_of_even.append(num**3)
cubes_of_even
Out[202]:
In [203]:
# equivalent list comprehension
# syntax: [expression for variable in iterable if condition]
cubes_of_even = [num**3 for num in nums if num % 2 == 0]
cubes_of_even
Out[203]:
In [204]:
# for loop to cube even numbers and square odd numbers
cubes_and_squares = []
for num in nums:
if num % 2 == 0:
cubes_and_squares.append(num**3)
else:
cubes_and_squares.append(num**2)
cubes_and_squares
Out[204]:
In [205]:
# equivalent list comprehension (using a ternary expression)
# syntax: [true_condition if condition else false_condition for variable in iterable]
cubes_and_squares = [num**3 if num % 2 == 0 else num**2 for num in nums]
cubes_and_squares
Out[205]:
In [206]:
# for loop to flatten a 2d-matrix
matrix = [[1, 2], [3, 4]]
items = []
for row in matrix:
for item in row:
items.append(item)
items
Out[206]:
In [207]:
# equivalent list comprehension
items = [item for row in matrix
for item in row]
items
Out[207]:
In [208]:
fruits = ['apple', 'banana', 'cherry']
unique_lengths = {len(fruit) for fruit in fruits}
unique_lengths
Out[208]:
In [209]:
fruit_lengths = {fruit:len(fruit) for fruit in fruits}
fruit_lengths
Out[209]:
In [210]:
fruit_indices = {fruit:index for index, fruit in enumerate(fruits)}
fruit_indices
Out[210]:
In [211]:
simpsons = ['homer', 'marge', 'bart']
map(len, simpsons)
Out[211]:
In [212]:
# equivalent list comprehension
[len(word) for word in simpsons]
Out[212]:
In [213]:
map(lambda word: word[-1], simpsons)
Out[213]:
In [214]:
# equivalent list comprehension
[word[-1] for word in simpsons]
Out[214]:
In [215]:
nums = range(5)
filter(lambda x: x % 2 == 0, nums)
Out[215]:
In [216]:
# equivalent list comprehension
[num for num in nums if num % 2 == 0]
Out[216]: