Installing the Spyder IDE
input()
function does not work well with your Spyder IDE from Anaconda Distribution, install the Spyder IDE in addition to Anaconda.Shortcuts
F9 runs a current line (where the blinking cursor bar is) or selected lines.
Home/End moves the blinking cursor bar to the beginning/end of the line.
PgUp/PgDn moves the blinking cursor bar to the top/bottom line of the script on the screen.
Shortcuts
Ctrl + Enter/Return runs a current cell, defined by # %%
.
Incidentally, Ctrl + Enter/Return is the keyboard shortcut for running the selection (or current line) in R Studio, not Spyder, which may be where I sometimes got confused.
Shortcuts
Mac
#
.Windows
#
.# %%
defines a coding block in Spyder IDE.More Shortcuts
In the previous classes, we started with some of Python’s basic data types: booleans, integers, floats, and strings.
Why does Python contain both lists and tuples?
Tuples are immutable; when we assign elements (only once) to a tuple, they’re baked in the cake and can’t be changed.
Lists are mutable, meaning we can insert and delete elements with great enthusiasm.
Create with Commas and ()
empty_tuple = ()
one_geneseo = 'Geneseo',
one_geneseo = ('Geneseo',)
one_geneseo = ('Geneseo')
suny_tuple = 'Geneseo', 'Borckport', 'Oswego'
suny_tuple = ('Geneseo', 'Borckport', 'Oswego')
one_geneseo = 'Geneseo',type(one_geneseo)type('Groucho',)type(('Groucho',))
suny_tuple = ('Geneseo', 'Borckport', 'Oswego')a, b, c = suny_tupleabc
password = 'swordfish'icecream = 'tuttifrutti'password, icecream = icecream, passwordpasswordicecream
tuple()
suny_list = ['Geneseo', 'Borckport', 'Oswego']tuple = tuple(suny_list)
+
('Geneseo',) + ('Borckport', 'Oswego')
*
+
:('yada',) * 3
a = (7, 2)b = (7, 2, 9)a == ba <= ba < b
for
and in
words = ('fresh','out', 'of', 'ideas')for word in words: print(word)
t1 = ('Fee', 'Fie', 'Foe')id(t1)t2 = ('Flop',)t1 + t2t1 += t2id(t1)
Lists are good for keeping track of things by their order, especially when the order and contents might change.
Lists are mutable---we can change a list in place, add new elements, and delete or replace existing elements.
The same value can occur more than once in a list.
Create with []
empty_list = [ ]weekdays = ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday']big_birds = ['emu', 'ostrich', 'cassowary']first_names = ['Mary', 'Susan', 'Nicholas', 'Nicholas', 'Michael']leap_years = [2012, 2016, 2020]
list()
We can also make an empty list with the list()
function.
list()
function also converts other iterable data types (such as tuples, strings, sets, and dictionaries) to lists.
another_empty_list = list()another_empty_listlist('cat')a_tuple = ('ready', 'fire', 'aim')list(a_tuple)
split()
split()
to chop a string into a list by some separator:coffee_day = '10/1/2022'coffee_day.split('/')splitme = 'a/b//c/d///e'splitme.split('/')splitme.split('//')
[offset]
suny = ['Geneseo', 'Brockport', 'Oswego']
suny[0]suny[1]suny[2]suny[5]
suny[-1]suny[-2]suny[-3]suny[-5]
suny = ['Geneseo', 'Brockport', 'Oswego']suny[0:2] # A slice of a list is also a list.
suny[::2]suny[::-2]suny[::-1]
suny[4:]suny[-6:]suny[-6:-2]suny[-6:-4]
reverse()
list.reverse()
:suny.reverse()suny
append()
append()
function adds items to the end of the list.suny = ['Geneseo', 'Brockport', 'Oswego']suny.append('Buffalo')sunysuny = ['Geneseo', 'Brockport', 'Oswego']others = ['Buffalo', 'Cortland']suny.append(others)suny
insert()
insert()
.suny = ['Geneseo', 'Brockport', 'Oswego']suny.insert(2, 'Buffalo')sunysuny.insert(10, 'Cortland')suny
*
. The same works for a list:["blah"] * 3suny = ['Geneseo', 'Brockport', 'Oswego']suny * 2
extend()
or +
extend()
or +
.suny = ['Geneseo', 'Brockport', 'Oswego']others = ['Buffalo', 'Cortland']suny.extend(others)sunysuny = ['Geneseo', 'Brockport', 'Oswego']others = ['Buffalo', 'Cortland']suny += otherssuny
[offset]
suny = ['Geneseo', 'Brockport', 'Oswego']suny[2] = 'Buffalo'suny
numbers = [1, 2, 3, 4]numbers[1:3] = ['eight', 'nine']numbers
numbers = [1, 2, 3, 4]numbers[1:3] = [7, 8, 9]numbers
del
del
statement to delete an item by its position in a list.suny = ['Geneseo', 'Brockport', 'Oswego', 'Rochester']suny[-1]del suny[-1] suny
remove()
remove()
to delete it by value.suny = ['Geneseo', 'Brockport', 'Oswego', 'Rochester']suny.remove('Rochester')sunysuny = ['Geneseo', 'Brockport', 'Oswego', 'Rochester', 'Rochester']suny.remove('Rochester')suny
pop()
pop()
.pop()
with an offset, it will return the item at that offset; with no argument, it uses -1.suny = ['Geneseo', 'Brockport', 'Oswego', 'Rochester']suny.pop()sunysuny.pop(1)suny
clear()
clear()
to clear a list of all its elements:suny_roc = ['Rochester', 'Rochester', 'Rochester', 'Rochester']suny.clear()suny
index()
index()
:suny = ['Geneseo', 'Brockport', 'Oswego', 'Buffalo']suny.index('Geneseo')suny = ['Geneseo', 'Brockport', 'Oswego', 'Geneseo']suny.index('Geneseo')
in
in
:suny = ['Geneseo', 'Brockport', 'Oswego', 'Buffalo']'Geneseo' in suny'Rochester' in sunywords = ['a', 'deer', 'a' 'male', 'deer']'deer' in words
count()
count()
:suny = ['Geneseo', 'Brockport', 'Oswego', 'Buffalo']suny.count('Geneseo')suny.count('Rochester')mcdonald = ['cheeseburger', 'cheeseburger', 'cheeseburger']mcdonald.count('cheeseburger')
join()
join()
is a string method, not a list method.suny = ['Geneseo', 'Brockport', 'Oswego', 'Buffalo']', '.join(suny)
suny.join(', ')
.join()
is a string or any iterable sequence of strings (including a list), and its output is a string.sort()
or sorted()
sort()
sorts the list itself, in place.sorted()
returns a sorted copy of the list.suny = ['Geneseo', 'Brockport', 'Oswego']sorted_suny = sorted(suny)sorted_sunysuny
suny.sort()suny
sort()
or sorted()
reverse=True
to set it to descending.numbers = [2, 1, 4.0, 3]numbers.sort()numbersnumbers = [2, 1, 4.0, 3]numbers.sort(reverse=True)numbers
suny = ['Geneseo', 'Brockport', 'Oswego']sorted_suny = sorted(suny, reverse=True)sorted_suny
len()
len()
returns the number of items in a list:suny = ['Geneseo', 'Brockport', 'Oswego']len(suny)
=
a = [1, 2, 3]b = aba[0] = 'suprise'a
b
now?b[0] = 'I hate suprises'b
a
now?We can copy the values of a list to an independent, fresh list by using (1) the list copy()
method, (2) the list()
conversion function, or (3) the list slice [:]
:
a = [1, 2, 3]b = a.copy()c = list(a)d = a[:]a[0] = 'integer lists'
b
, c
, and d
are copies of a
: a
refers.b
, c
, and d
now?copy()
method, (2) the list()
conversion function, or (3) the list slice [:]
works well if the list values are all immutable.a = [1, 2, [8, 9]]b = a.copy()c = list(a)d = a[:]a[2][1] = 10
b
, c
, and d
are copies of a
.The value of a[2]
is now a list, and its elements can be changed.
b
, c
, and d
now?deepcopy()
function:import copya = [1, 2, [8, 9]]b = copy.deepcopy(a)a[2][1] = 10ab
deepcopy()
can handle deeply nested lists, dictionaries, and other objects.
We'll discuss more about import
soon.
==
, <
, and so on.a = [7, 2]b = [7, 2, 9]a == ba <= ba < b
a
is shorter than list b
, and all of its elements are equal, a
is less than b
. Iterate with for
and in
for
loop is quite common to iterate over lists.cheeses = ['brie', 'gjetost', 'havarti']for cheese in cheeses: print(cheese)
break
ends the for loop and continue
steps to the next iteration:cheeses = ['brie', 'gjetost', 'havarti']for cheese in cheeses: if cheese.startswith('g'): print("I won't eat anything that starts with 'g'") break else: print(cheese)
else
if the for completed without a break
:cheeses = ['brie', 'gjetost', 'havarti']for cheese in cheeses: if cheese.startswith('x'): print("I won't eat anything that starts with 'x'") break else: print(cheese)else: print("Didn't find anything that started with 'x'")
for
never ran, control goes to the else
:cheeses = []for cheese in cheeses: print('This shop has some lovely', cheese) breakelse: # no break means no cheese print('This is not much of a cheese shop, is it?')
Iterate Multiple Sequences with zip()
zip()
function.days = ['Monday', 'Tuesday', 'Wednesday']fruits = ['banana', 'orange', 'peach']drinks = ['coffee', 'coffee', 'coffee']desserts = ['tiramisu', 'ice cream', 'pie', 'pudding']for day, fruit, drink, dessert in zip(days, fruits, drinks, desserts): print(day, ": drink", drink, "- eat", fruit, "- enjoy", dessert)
zip()
to walk through multiple sequences and make tuples from items at the same offsets.english = 'Monday', 'Tuesday', 'Wednesday'french = 'Lundi', 'Mardi', 'Mercredi'list( zip(english, french) )dict( zip(english, french) )
dict()
function can create dictionaries from two-item sequences like tuples, lists, or strings.Create a List with a Comprehension
Here, we look at how to create a list with a list comprehension, which incorporates the for
/in
iteration that we just saw.
number_list = []number_list.append(1)number_list.append(2)number_list.append(3)number_list.append(4)number_list.append(5)
number_list = []for number in range(1, 6): number_list.append(number)number_list
number_list = list(range(1, 6))number_list
number_list = [number for number in range(1,6)]number_list
Create a List with a Comprehension
number_list = [number for number in range(1,6)]number_list
In the first line, we need the first number
variable to produce values for the list: that is, to put a result of the loop into number_list
.
The second number
is part of the for loop.
number
in example 1 is an expression, try this variant:number_list = [number - 1 for number in range(1,6)]number_list
a_list = [number for number in range(1,6) if number % 2 == 1]
a_list = []for number in range(1,6): if number % 2 == 1: a_list.append(number)
Create a List with a Comprehension
for ...
clauses in the corresponding comprehension.rows = range(1,4)cols = range(1,3)for row in rows: for col in cols: print(row, col)
rows = range(1,4)cols = range(1,3)cells = [(row, col) for row in rows for col in cols]for cell in cells: print(cell)
rows = range(1,4)cols = range(1,3)cells = [(row, col) for row in rows for col in cols]for row, col in cells: print(row, col)
Lists of Lists
small_birds = ['hummingbird', 'finch']extinct_birds = ['dodo', 'passenger pigeon', 'Norwegian Blue']carol_birds = [3, 'French hens', 2, 'turtledoves']all_birds = [small_birds, extinct_birds, 'macaw', carol_birds]
all_birds
, a list of lists, look like?all_birdsall_birds[0]all_birds[1]all_birds[1][0] # [0] refers to the first item in that inner list.
Tuples Versus Lists
append()
, insert()
, and so on—because they can’t be modified after creation.There Are No Tuple Comprehensions
number_thing = (number for number in range(1, 6))type(number_thing)
Class Exercises 1
Create a list called years_list
, starting with the year of your birth, and each year thereafter until the year of your fifth birthday. For example, if you were born in 2003, the list would be years_list = [2003, 2004, 2005, 2006, 2007, 2008].
In which of these years was your third birthday? Remember, you were 0 years of age for your first year.
In which year in years_list
were you the oldest?
Class Exercises 2
Make a list called things
with these three strings as elements: "mozzarella"
, "cinderella"
, "salmonella"
.
Capitalize the element in things
that refers to a person and then print the list. Did it change the element in the list?
Make the cheesy element of things
all uppercase and then print the list.
Delete the disease element of things
, and then print the list.
Class Exercises 3
Create a list called surprise
with the elements "Groucho"
, "Chico"
, and "Harpo"
.
Lowercase the last element of the surprise
list, reverse it, and then capitalize it.
Class Exercises 4
even
of the even numbers in range(10)
.A dictionary is similar to a list, but the order of items doesn’t matter, and they aren’t selected by an offset such as 0 or 1.
Instead, we specify a unique key to associate with each value.
This key is often a string, but it can actually be any of Python’s immutable types: boolean, integer, float, tuple, string, and others.
Dictionaries are mutable, so we can add, delete, and change their key-value elements.
Create with {}
{}
) around comma-separated key : value pairs.empty_dict = {}empty_dict
Let’s make a small dictionary with quotes from Ambrose Bierce’s The Devil’s Dictionary:
bierce = {"day": "A period of twenty-four hours, mostly misspent", "positive": "Mistaken at the top of one's voice", "misfortune": "The kind of fortune that never misses"}bierce
Create with dict()
dict()
function.acme_customer = {'first': 'Wile', 'middle': 'E', 'last': 'Coyote'}acme_customeracme_customer = dict(first = "Wile", middle = "E", last = "Coyote")acme_customer
dict()
need to be legal variable names (no spaces, no reserved words):x = dict(name="Elmer", def="hunter")
Convert with dict()
dict()
to convert two-value sequences into a dictionary.lol = [ ['a', 'b'], ['c', 'd'], ['e', 'f'] ]dict(lol)
lot = [ ('a', 'b'), ('c', 'd'), ('e', 'f') ]dict(lot)
tol = ( ['a', 'b'], ['c', 'd'], ['e', 'f'] )dict(tol)
los = [ 'ab', 'cd', 'ef' ]dict(los)
tos = ( 'ab', 'cd', 'ef' )dict(tos)
Add or Change an Item by [ key ]
Adding an item to a dictionary is not complicated.
Just refer to the item by its key and assign a value.
If the key was already present in the dictionary, the existing value is replaced by the new one.
If the key is new, it’s added to the dictionary with its value.
Add or Change an Item by [ key ]
st_city = { 'MN': 'Rochester', 'WY': 'Laramie', 'CO': 'Denver' }st_city
st_city['NY'] = 'Rocjester'st_city
st_city['NY'] = 'Rochester'st_city
city_st = { 'Rochester': 'MN', 'Laramie': 'WY', 'Denver': 'CO', 'Rochester': 'NY' }city_st
Get an Item by [key]
or with get()
city_st = { 'Rochester': 'MN', 'Laramie': 'WY', 'Denver': 'CO', 'Rochester': 'NY' }city_st['Denver']
city_st['Buffalo']
in
and get()
in
:'Buffalo' in city_st
get()
function.city_st.get('Denver')
get()
function.city_st('Buffalo', 'Not in city_st')
get()
function.None
, which displays nothing in the console.city_st('Buffalo')
Get All Keys with keys()
keys()
to get all of the keys in a dictionary. signals = {'green': 'go', 'yellow': 'go faster', 'red': 'smile for the camera'}signals.keys()list( signals.keys() ) # to turn the result into a list object.
Get All Values with values()
values()
:signals = {'green': 'go', 'yellow': 'go faster', 'red': 'smile for the camera'}signals.values()list( signals.values() ) # to turn the result into a list object.
Get All Key-Value Pairs with items()
items()
function:signals = {'green': 'go', 'yellow': 'go faster', 'red': 'smile for the camera'}signals.items()list( signals.items() ) # to turn the result into a list object.
Get Length with len()
signals = {'green': 'go', 'yellow': 'go faster', 'red': 'smile for the camera'}len(signals)
Combine Dictionaries with {**a, **b}
**
:first = {'a': 'agony', 'b': 'bliss'}second = {'b': 'bagels', 'c': 'candy'}{**first, **second}third = {'d': 'donuts'}{**first, **third, **second}
Combine Dictionaries with update()
update()
function to copy the keys and values of one dictionary into another.st_city
with other_city
st_city = { 'MN': 'Rochester', 'WY': 'Laramie', 'CO': 'Denver', 'NY': 'Rochester' }other_city = {'MA': 'Boston'}st_city.update(other_city)
Combine Dictionaries with update()
first = {'a': 1, 'b': 2}second = {'b': 'platypus'}first.update(second)first
Delete an Item by Key with del
del
:del st_city['NY']st_city
Get an Item by Key and Delete It with pop()
pop()
combines get() and del. pop()
a key and it exists in the dictionary, it returns the matching value and deletes the key-value pair. pop()
a second default argument, all is well and the dictionary is not changed:len(st_city)st_city.pop('MN')len(st_city)st_city.pop('MN')st_city.pop('MN', 'Not exist')
Delete All Items with clear()
clear()
or just reassign an empty dictionary ({}
) to the name:st_city.clear()st_cityst_city = { 'MN': 'Rochester', 'WY': 'Laramie', 'CO': 'Denver', 'NY': 'Rochester' }st_city = {}st_city
Test for a Key with in
in
:st_city = { 'MN': 'Rochester', 'WY': 'Laramie', 'CO': 'Denver', 'NY': 'Rochester' }'NY' in st_city'WY' in st_city'CA' in st_city
Assign with =
signals = { 'green': 'go', 'yellow': 'go faster', 'red': 'smile for the camera' }save_signals = signalssignals['blue'] = 'confuse everyone'signals
save_signals
now? Assign with =
copy()
:signals = { 'green': 'go', 'yellow': 'go faster', 'red': 'smile for the camera' }original_signals = signals.copy()signals['blue'] = 'confuse everyone'signals
original_signals
now? Copy Everything with deepcopy()
signals
was a list instead of a single string:signals = { 'green': 'go', 'yellow': 'go faster', 'red': ['stop', 'smile'] }signals_copy = signals.copy()signals
signals_copy
? Copy Everything with deepcopy()
signals = { 'green': 'go', 'yellow': 'go faster', 'red': ['stop', 'smile'] }signals_copy = signals.copy()signals['red'][1] = 'sweat'signals
signals_copy
? Copy Everything with deepcopy()
deepcopy()
:import copysignals = { 'green': 'go', 'yellow': 'go faster', 'red': ['stop', 'smile'] }signals_deepcopy = copy.deepcopy(signals)signalssignals_deepcopysignals['red'][1] = 'sweat'signals
signals_deepcopy
?Compare Dictionaries
==
and !=
:a = {1:1, 2:2, 3:3}b = {3:3, 1:1, 2:2}a == ba != ba <= b # does it work?
Iterate with for
and in
keys()
function) returns the keys. accusation = {'room': 'ballroom', 'weapon': 'lead pipe', 'person': 'Col. Mustard'}for card in accusation: # or, for card in accusation.keys(): print(card)
Iterate with for
and in
values()
function:accusation = {'room': 'ballroom', 'weapon': 'lead pipe', 'person': 'Col. Mustard'}for value in accusation.values(): print(value)
Iterate with for
and in
items()
function:accusation = {'room': 'ballroom', 'weapon': 'lead pipe', 'person': 'Col. Mustard'}for item in accusation.items(): print(item)
Iterate with for
and in
items()
, let's assign the first value (the key) to card, and the second (the value) to contents:accusation = {'room': 'ballroom', 'weapon': 'lead pipe', 'person': 'Col. Mustard'}for card, contents in accusation.items(): print('Card', card, 'has the contents', contents)
Dictionary Comprehensions
Dictionary Comprehensions
word = 'letters'letter_counts = {letter: word.count(letter) for letter in word}letter_counts
Dictionary Comprehensions
word = 'letters'letter_counts = {letter: word.count(letter) for letter in set(word)}letter_counts
Dictionary Comprehensions
vowels = 'aeiou'word = 'onomatopoeia'vowel_counts = {letter: word.count(letter) for letter in set(word) if letter in vowels}vowel_counts
Installing the Spyder IDE
input()
function does not work well with your Spyder IDE from Anaconda Distribution, install the Spyder IDE in addition to Anaconda.Keyboard shortcuts
↑, ←, Pg Up, k | Go to previous slide |
↓, →, Pg Dn, Space, j | Go to next slide |
Home | Go to first slide |
End | Go to last slide |
Number + Return | Go to specific slide |
b / m / f | Toggle blackout / mirrored / fullscreen mode |
c | Clone slideshow |
p | Toggle presenter mode |
t | Restart the presentation timer |
?, h | Toggle this help |
o | Tile View: Overview of Slides |
Esc | Back to slideshow |
Installing the Spyder IDE
input()
function does not work well with your Spyder IDE from Anaconda Distribution, install the Spyder IDE in addition to Anaconda.Shortcuts
F9 runs a current line (where the blinking cursor bar is) or selected lines.
Home/End moves the blinking cursor bar to the beginning/end of the line.
PgUp/PgDn moves the blinking cursor bar to the top/bottom line of the script on the screen.
Shortcuts
Ctrl + Enter/Return runs a current cell, defined by # %%
.
Incidentally, Ctrl + Enter/Return is the keyboard shortcut for running the selection (or current line) in R Studio, not Spyder, which may be where I sometimes got confused.
Shortcuts
Mac
#
.Windows
#
.# %%
defines a coding block in Spyder IDE.More Shortcuts
In the previous classes, we started with some of Python’s basic data types: booleans, integers, floats, and strings.
Why does Python contain both lists and tuples?
Tuples are immutable; when we assign elements (only once) to a tuple, they’re baked in the cake and can’t be changed.
Lists are mutable, meaning we can insert and delete elements with great enthusiasm.
Create with Commas and ()
empty_tuple = ()
one_geneseo = 'Geneseo',
one_geneseo = ('Geneseo',)
one_geneseo = ('Geneseo')
suny_tuple = 'Geneseo', 'Borckport', 'Oswego'
suny_tuple = ('Geneseo', 'Borckport', 'Oswego')
one_geneseo = 'Geneseo',type(one_geneseo)type('Groucho',)type(('Groucho',))
suny_tuple = ('Geneseo', 'Borckport', 'Oswego')a, b, c = suny_tupleabc
password = 'swordfish'icecream = 'tuttifrutti'password, icecream = icecream, passwordpasswordicecream
tuple()
suny_list = ['Geneseo', 'Borckport', 'Oswego']tuple = tuple(suny_list)
+
('Geneseo',) + ('Borckport', 'Oswego')
*
+
:('yada',) * 3
a = (7, 2)b = (7, 2, 9)a == ba <= ba < b
for
and in
words = ('fresh','out', 'of', 'ideas')for word in words: print(word)
t1 = ('Fee', 'Fie', 'Foe')id(t1)t2 = ('Flop',)t1 + t2t1 += t2id(t1)
Lists are good for keeping track of things by their order, especially when the order and contents might change.
Lists are mutable---we can change a list in place, add new elements, and delete or replace existing elements.
The same value can occur more than once in a list.
Create with []
empty_list = [ ]weekdays = ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday']big_birds = ['emu', 'ostrich', 'cassowary']first_names = ['Mary', 'Susan', 'Nicholas', 'Nicholas', 'Michael']leap_years = [2012, 2016, 2020]
list()
We can also make an empty list with the list()
function.
list()
function also converts other iterable data types (such as tuples, strings, sets, and dictionaries) to lists.
another_empty_list = list()another_empty_listlist('cat')a_tuple = ('ready', 'fire', 'aim')list(a_tuple)
split()
split()
to chop a string into a list by some separator:coffee_day = '10/1/2022'coffee_day.split('/')splitme = 'a/b//c/d///e'splitme.split('/')splitme.split('//')
[offset]
suny = ['Geneseo', 'Brockport', 'Oswego']
suny[0]suny[1]suny[2]suny[5]
suny[-1]suny[-2]suny[-3]suny[-5]
suny = ['Geneseo', 'Brockport', 'Oswego']suny[0:2] # A slice of a list is also a list.
suny[::2]suny[::-2]suny[::-1]
suny[4:]suny[-6:]suny[-6:-2]suny[-6:-4]
reverse()
list.reverse()
:suny.reverse()suny
append()
append()
function adds items to the end of the list.suny = ['Geneseo', 'Brockport', 'Oswego']suny.append('Buffalo')sunysuny = ['Geneseo', 'Brockport', 'Oswego']others = ['Buffalo', 'Cortland']suny.append(others)suny
insert()
insert()
.suny = ['Geneseo', 'Brockport', 'Oswego']suny.insert(2, 'Buffalo')sunysuny.insert(10, 'Cortland')suny
*
. The same works for a list:["blah"] * 3suny = ['Geneseo', 'Brockport', 'Oswego']suny * 2
extend()
or +
extend()
or +
.suny = ['Geneseo', 'Brockport', 'Oswego']others = ['Buffalo', 'Cortland']suny.extend(others)sunysuny = ['Geneseo', 'Brockport', 'Oswego']others = ['Buffalo', 'Cortland']suny += otherssuny
[offset]
suny = ['Geneseo', 'Brockport', 'Oswego']suny[2] = 'Buffalo'suny
numbers = [1, 2, 3, 4]numbers[1:3] = ['eight', 'nine']numbers
numbers = [1, 2, 3, 4]numbers[1:3] = [7, 8, 9]numbers
del
del
statement to delete an item by its position in a list.suny = ['Geneseo', 'Brockport', 'Oswego', 'Rochester']suny[-1]del suny[-1] suny
remove()
remove()
to delete it by value.suny = ['Geneseo', 'Brockport', 'Oswego', 'Rochester']suny.remove('Rochester')sunysuny = ['Geneseo', 'Brockport', 'Oswego', 'Rochester', 'Rochester']suny.remove('Rochester')suny
pop()
pop()
.pop()
with an offset, it will return the item at that offset; with no argument, it uses -1.suny = ['Geneseo', 'Brockport', 'Oswego', 'Rochester']suny.pop()sunysuny.pop(1)suny
clear()
clear()
to clear a list of all its elements:suny_roc = ['Rochester', 'Rochester', 'Rochester', 'Rochester']suny.clear()suny
index()
index()
:suny = ['Geneseo', 'Brockport', 'Oswego', 'Buffalo']suny.index('Geneseo')suny = ['Geneseo', 'Brockport', 'Oswego', 'Geneseo']suny.index('Geneseo')
in
in
:suny = ['Geneseo', 'Brockport', 'Oswego', 'Buffalo']'Geneseo' in suny'Rochester' in sunywords = ['a', 'deer', 'a' 'male', 'deer']'deer' in words
count()
count()
:suny = ['Geneseo', 'Brockport', 'Oswego', 'Buffalo']suny.count('Geneseo')suny.count('Rochester')mcdonald = ['cheeseburger', 'cheeseburger', 'cheeseburger']mcdonald.count('cheeseburger')
join()
join()
is a string method, not a list method.suny = ['Geneseo', 'Brockport', 'Oswego', 'Buffalo']', '.join(suny)
suny.join(', ')
.join()
is a string or any iterable sequence of strings (including a list), and its output is a string.sort()
or sorted()
sort()
sorts the list itself, in place.sorted()
returns a sorted copy of the list.suny = ['Geneseo', 'Brockport', 'Oswego']sorted_suny = sorted(suny)sorted_sunysuny
suny.sort()suny
sort()
or sorted()
reverse=True
to set it to descending.numbers = [2, 1, 4.0, 3]numbers.sort()numbersnumbers = [2, 1, 4.0, 3]numbers.sort(reverse=True)numbers
suny = ['Geneseo', 'Brockport', 'Oswego']sorted_suny = sorted(suny, reverse=True)sorted_suny
len()
len()
returns the number of items in a list:suny = ['Geneseo', 'Brockport', 'Oswego']len(suny)
=
a = [1, 2, 3]b = aba[0] = 'suprise'a
b
now?b[0] = 'I hate suprises'b
a
now?We can copy the values of a list to an independent, fresh list by using (1) the list copy()
method, (2) the list()
conversion function, or (3) the list slice [:]
:
a = [1, 2, 3]b = a.copy()c = list(a)d = a[:]a[0] = 'integer lists'
b
, c
, and d
are copies of a
: a
refers.b
, c
, and d
now?copy()
method, (2) the list()
conversion function, or (3) the list slice [:]
works well if the list values are all immutable.a = [1, 2, [8, 9]]b = a.copy()c = list(a)d = a[:]a[2][1] = 10
b
, c
, and d
are copies of a
.The value of a[2]
is now a list, and its elements can be changed.
b
, c
, and d
now?deepcopy()
function:import copya = [1, 2, [8, 9]]b = copy.deepcopy(a)a[2][1] = 10ab
deepcopy()
can handle deeply nested lists, dictionaries, and other objects.
We'll discuss more about import
soon.
==
, <
, and so on.a = [7, 2]b = [7, 2, 9]a == ba <= ba < b
a
is shorter than list b
, and all of its elements are equal, a
is less than b
. Iterate with for
and in
for
loop is quite common to iterate over lists.cheeses = ['brie', 'gjetost', 'havarti']for cheese in cheeses: print(cheese)
break
ends the for loop and continue
steps to the next iteration:cheeses = ['brie', 'gjetost', 'havarti']for cheese in cheeses: if cheese.startswith('g'): print("I won't eat anything that starts with 'g'") break else: print(cheese)
else
if the for completed without a break
:cheeses = ['brie', 'gjetost', 'havarti']for cheese in cheeses: if cheese.startswith('x'): print("I won't eat anything that starts with 'x'") break else: print(cheese)else: print("Didn't find anything that started with 'x'")
for
never ran, control goes to the else
:cheeses = []for cheese in cheeses: print('This shop has some lovely', cheese) breakelse: # no break means no cheese print('This is not much of a cheese shop, is it?')
Iterate Multiple Sequences with zip()
zip()
function.days = ['Monday', 'Tuesday', 'Wednesday']fruits = ['banana', 'orange', 'peach']drinks = ['coffee', 'coffee', 'coffee']desserts = ['tiramisu', 'ice cream', 'pie', 'pudding']for day, fruit, drink, dessert in zip(days, fruits, drinks, desserts): print(day, ": drink", drink, "- eat", fruit, "- enjoy", dessert)
zip()
to walk through multiple sequences and make tuples from items at the same offsets.english = 'Monday', 'Tuesday', 'Wednesday'french = 'Lundi', 'Mardi', 'Mercredi'list( zip(english, french) )dict( zip(english, french) )
dict()
function can create dictionaries from two-item sequences like tuples, lists, or strings.Create a List with a Comprehension
Here, we look at how to create a list with a list comprehension, which incorporates the for
/in
iteration that we just saw.
number_list = []number_list.append(1)number_list.append(2)number_list.append(3)number_list.append(4)number_list.append(5)
number_list = []for number in range(1, 6): number_list.append(number)number_list
number_list = list(range(1, 6))number_list
number_list = [number for number in range(1,6)]number_list
Create a List with a Comprehension
number_list = [number for number in range(1,6)]number_list
In the first line, we need the first number
variable to produce values for the list: that is, to put a result of the loop into number_list
.
The second number
is part of the for loop.
number
in example 1 is an expression, try this variant:number_list = [number - 1 for number in range(1,6)]number_list
a_list = [number for number in range(1,6) if number % 2 == 1]
a_list = []for number in range(1,6): if number % 2 == 1: a_list.append(number)
Create a List with a Comprehension
for ...
clauses in the corresponding comprehension.rows = range(1,4)cols = range(1,3)for row in rows: for col in cols: print(row, col)
rows = range(1,4)cols = range(1,3)cells = [(row, col) for row in rows for col in cols]for cell in cells: print(cell)
rows = range(1,4)cols = range(1,3)cells = [(row, col) for row in rows for col in cols]for row, col in cells: print(row, col)
Lists of Lists
small_birds = ['hummingbird', 'finch']extinct_birds = ['dodo', 'passenger pigeon', 'Norwegian Blue']carol_birds = [3, 'French hens', 2, 'turtledoves']all_birds = [small_birds, extinct_birds, 'macaw', carol_birds]
all_birds
, a list of lists, look like?all_birdsall_birds[0]all_birds[1]all_birds[1][0] # [0] refers to the first item in that inner list.
Tuples Versus Lists
append()
, insert()
, and so on—because they can’t be modified after creation.There Are No Tuple Comprehensions
number_thing = (number for number in range(1, 6))type(number_thing)
Class Exercises 1
Create a list called years_list
, starting with the year of your birth, and each year thereafter until the year of your fifth birthday. For example, if you were born in 2003, the list would be years_list = [2003, 2004, 2005, 2006, 2007, 2008].
In which of these years was your third birthday? Remember, you were 0 years of age for your first year.
In which year in years_list
were you the oldest?
Class Exercises 2
Make a list called things
with these three strings as elements: "mozzarella"
, "cinderella"
, "salmonella"
.
Capitalize the element in things
that refers to a person and then print the list. Did it change the element in the list?
Make the cheesy element of things
all uppercase and then print the list.
Delete the disease element of things
, and then print the list.
Class Exercises 3
Create a list called surprise
with the elements "Groucho"
, "Chico"
, and "Harpo"
.
Lowercase the last element of the surprise
list, reverse it, and then capitalize it.
Class Exercises 4
even
of the even numbers in range(10)
.A dictionary is similar to a list, but the order of items doesn’t matter, and they aren’t selected by an offset such as 0 or 1.
Instead, we specify a unique key to associate with each value.
This key is often a string, but it can actually be any of Python’s immutable types: boolean, integer, float, tuple, string, and others.
Dictionaries are mutable, so we can add, delete, and change their key-value elements.
Create with {}
{}
) around comma-separated key : value pairs.empty_dict = {}empty_dict
Let’s make a small dictionary with quotes from Ambrose Bierce’s The Devil’s Dictionary:
bierce = {"day": "A period of twenty-four hours, mostly misspent", "positive": "Mistaken at the top of one's voice", "misfortune": "The kind of fortune that never misses"}bierce
Create with dict()
dict()
function.acme_customer = {'first': 'Wile', 'middle': 'E', 'last': 'Coyote'}acme_customeracme_customer = dict(first = "Wile", middle = "E", last = "Coyote")acme_customer
dict()
need to be legal variable names (no spaces, no reserved words):x = dict(name="Elmer", def="hunter")
Convert with dict()
dict()
to convert two-value sequences into a dictionary.lol = [ ['a', 'b'], ['c', 'd'], ['e', 'f'] ]dict(lol)
lot = [ ('a', 'b'), ('c', 'd'), ('e', 'f') ]dict(lot)
tol = ( ['a', 'b'], ['c', 'd'], ['e', 'f'] )dict(tol)
los = [ 'ab', 'cd', 'ef' ]dict(los)
tos = ( 'ab', 'cd', 'ef' )dict(tos)
Add or Change an Item by [ key ]
Adding an item to a dictionary is not complicated.
Just refer to the item by its key and assign a value.
If the key was already present in the dictionary, the existing value is replaced by the new one.
If the key is new, it’s added to the dictionary with its value.
Add or Change an Item by [ key ]
st_city = { 'MN': 'Rochester', 'WY': 'Laramie', 'CO': 'Denver' }st_city
st_city['NY'] = 'Rocjester'st_city
st_city['NY'] = 'Rochester'st_city
city_st = { 'Rochester': 'MN', 'Laramie': 'WY', 'Denver': 'CO', 'Rochester': 'NY' }city_st
Get an Item by [key]
or with get()
city_st = { 'Rochester': 'MN', 'Laramie': 'WY', 'Denver': 'CO', 'Rochester': 'NY' }city_st['Denver']
city_st['Buffalo']
in
and get()
in
:'Buffalo' in city_st
get()
function.city_st.get('Denver')
get()
function.city_st('Buffalo', 'Not in city_st')
get()
function.None
, which displays nothing in the console.city_st('Buffalo')
Get All Keys with keys()
keys()
to get all of the keys in a dictionary. signals = {'green': 'go', 'yellow': 'go faster', 'red': 'smile for the camera'}signals.keys()list( signals.keys() ) # to turn the result into a list object.
Get All Values with values()
values()
:signals = {'green': 'go', 'yellow': 'go faster', 'red': 'smile for the camera'}signals.values()list( signals.values() ) # to turn the result into a list object.
Get All Key-Value Pairs with items()
items()
function:signals = {'green': 'go', 'yellow': 'go faster', 'red': 'smile for the camera'}signals.items()list( signals.items() ) # to turn the result into a list object.
Get Length with len()
signals = {'green': 'go', 'yellow': 'go faster', 'red': 'smile for the camera'}len(signals)
Combine Dictionaries with {**a, **b}
**
:first = {'a': 'agony', 'b': 'bliss'}second = {'b': 'bagels', 'c': 'candy'}{**first, **second}third = {'d': 'donuts'}{**first, **third, **second}
Combine Dictionaries with update()
update()
function to copy the keys and values of one dictionary into another.st_city
with other_city
st_city = { 'MN': 'Rochester', 'WY': 'Laramie', 'CO': 'Denver', 'NY': 'Rochester' }other_city = {'MA': 'Boston'}st_city.update(other_city)
Combine Dictionaries with update()
first = {'a': 1, 'b': 2}second = {'b': 'platypus'}first.update(second)first
Delete an Item by Key with del
del
:del st_city['NY']st_city
Get an Item by Key and Delete It with pop()
pop()
combines get() and del. pop()
a key and it exists in the dictionary, it returns the matching value and deletes the key-value pair. pop()
a second default argument, all is well and the dictionary is not changed:len(st_city)st_city.pop('MN')len(st_city)st_city.pop('MN')st_city.pop('MN', 'Not exist')
Delete All Items with clear()
clear()
or just reassign an empty dictionary ({}
) to the name:st_city.clear()st_cityst_city = { 'MN': 'Rochester', 'WY': 'Laramie', 'CO': 'Denver', 'NY': 'Rochester' }st_city = {}st_city
Test for a Key with in
in
:st_city = { 'MN': 'Rochester', 'WY': 'Laramie', 'CO': 'Denver', 'NY': 'Rochester' }'NY' in st_city'WY' in st_city'CA' in st_city
Assign with =
signals = { 'green': 'go', 'yellow': 'go faster', 'red': 'smile for the camera' }save_signals = signalssignals['blue'] = 'confuse everyone'signals
save_signals
now? Assign with =
copy()
:signals = { 'green': 'go', 'yellow': 'go faster', 'red': 'smile for the camera' }original_signals = signals.copy()signals['blue'] = 'confuse everyone'signals
original_signals
now? Copy Everything with deepcopy()
signals
was a list instead of a single string:signals = { 'green': 'go', 'yellow': 'go faster', 'red': ['stop', 'smile'] }signals_copy = signals.copy()signals
signals_copy
? Copy Everything with deepcopy()
signals = { 'green': 'go', 'yellow': 'go faster', 'red': ['stop', 'smile'] }signals_copy = signals.copy()signals['red'][1] = 'sweat'signals
signals_copy
? Copy Everything with deepcopy()
deepcopy()
:import copysignals = { 'green': 'go', 'yellow': 'go faster', 'red': ['stop', 'smile'] }signals_deepcopy = copy.deepcopy(signals)signalssignals_deepcopysignals['red'][1] = 'sweat'signals
signals_deepcopy
?Compare Dictionaries
==
and !=
:a = {1:1, 2:2, 3:3}b = {3:3, 1:1, 2:2}a == ba != ba <= b # does it work?
Iterate with for
and in
keys()
function) returns the keys. accusation = {'room': 'ballroom', 'weapon': 'lead pipe', 'person': 'Col. Mustard'}for card in accusation: # or, for card in accusation.keys(): print(card)
Iterate with for
and in
values()
function:accusation = {'room': 'ballroom', 'weapon': 'lead pipe', 'person': 'Col. Mustard'}for value in accusation.values(): print(value)
Iterate with for
and in
items()
function:accusation = {'room': 'ballroom', 'weapon': 'lead pipe', 'person': 'Col. Mustard'}for item in accusation.items(): print(item)
Iterate with for
and in
items()
, let's assign the first value (the key) to card, and the second (the value) to contents:accusation = {'room': 'ballroom', 'weapon': 'lead pipe', 'person': 'Col. Mustard'}for card, contents in accusation.items(): print('Card', card, 'has the contents', contents)
Dictionary Comprehensions
Dictionary Comprehensions
word = 'letters'letter_counts = {letter: word.count(letter) for letter in word}letter_counts
Dictionary Comprehensions
word = 'letters'letter_counts = {letter: word.count(letter) for letter in set(word)}letter_counts
Dictionary Comprehensions
vowels = 'aeiou'word = 'onomatopoeia'vowel_counts = {letter: word.count(letter) for letter in set(word) if letter in vowels}vowel_counts