SlideShare a Scribd company logo
lists and
(the amazing)
dictionaries
The plan!
Basics: data types (and operations & calculations)
Basics: conditionals & iteration
Basics: lists, tuples, dictionaries
Basics: writing functions
Reading & writing files: opening, parsing & formats
Working with numbers: numpy & scipy
Making plots: matplotlib & pylab
… if you guys want more after all of that …
Writing better code: functions, pep8, classes
Working with numbers: Numpy & Scipy (advanced)
Other modules: Pandas & Scikit-learn
Interactive notebooks: ipython & jupyter
Advanced topics: virtual environments & version control
data types for multiple things...
lists
[ 1, 2, 3, 100, 99 , 50]
strings
"wait, we already know these!"
tuples
(10, 11, 12, 100, 90, 80)
dictionaries
{"name": "Bob", "age": 33}
lists
# define a list:
mylist = [5, 3, 1, "a", [12, 14, 16],]
# indexing and slicing:
print mylist[2]
print mylist[:4]
# changing elements
mylist[2] = 300
print mylist
Using an existing list with methods:
mylist.method()
Finding things:
.index(element) ← first only
.count(element)
Removing things:
.pop(<pos>) ← returns element
.remove(element)
Adding things:
.append(element)
.insert(pos, element)
.extend(newlist)
also useful: len(list)
copying lists: list2 = list(list1)
lists, loops and conditionals
---- somefile.py ----
# lets take a close look at "range":
a = range(10)
print type(a) # (note: different in python 3)
lists, loops and conditionals
---- somefile.py ----
# lets take a close look at "range":
a = range(10)
print type(a) # (note: different in python 3)
# using lists in loops:
somelist = [1, 2, "a", "b", "hello", 3.0, 99]
for element in somelist:
print element, "is of type:", type(element)
lists, loops and conditionals
---- somefile.py ----
# lets take a close look at "range":
a = range(10)
print type(a) # (note: different in python 3)
# using lists in loops:
somelist = [1, 2, "a", "b", "hello", 3.0, 99]
for element in somelist:
print element, "is of type:", type(element)
# using lists in conditionals:
if "a" in somelist:
print "a is in the list"
Using in with lists:
for var in list:
do stuff in loop
if var in list:
do "True" block
else:
do "False" block
lists, loops and conditionals
---- somefile.py ----
# lets take a close look at "range":
a = range(10)
print type(a) # (note: different in python 3)
# using lists in loops:
somelist = [1, 2, "a", "b", "hello", 3.0, 99]
for element in somelist:
print element, "is of type:", type(element)
# using lists in conditionals:
if "a" in somelist:
print "a is in the list"
# using lists in tests and conditionals:
mylist = [1, 2, "a", "b", "hello", 99]
for a in range(100):
if a in mylist:
print a, "is in the list!"
Using in with lists:
for var in list:
do stuff in loop
if var in list:
do "True" block
else:
do "False" block
- you can download this from our drive: hamcakes_script
- How many ingredients are there in total (in the snack)?
- Are there any in the "snack" which are not in "pancakes" or "hamburger"? (add
these to the correct list)
- By majority vote: is it a pancake or hamburger?
hamcake!
# you should be able to copy-paste this :)
snack = [
"chocolate", "strawberries", "salad", "chocolate", "salad", "cheese", "cream", "cheese", "tomatoes", "bacon", "bacon", "tomatoes", "burger", "onions", "cheese",
"banana", "pineapple", "tomatoes", "bacon", "cheese", "burger", "salad", "tomatoes", "onions", "chocolate", "pineapple", "tomatoes", "onions", "salad",
"strawberries",
"egg", "cheese", "tomatoes", "burger", "bacon", "cream", "sugar", "burger", "ketchup", "salad", "chocolate", "cream", "egg", "sugar", "salad", "pineapple", "bacon",
"cheese", "bacon",
]
pancake = [ "chocolate", "strawberries", "chocolate", "cream", "pineapple", "sugar",]
hamburger = [ "tomatoes", "bacon", "cheese", "burger", "salad", "onions", "egg", ]
dictionaries!
---- animals.py ----
# Creating a dictionary. Note the use of "{" and "}"
# The ":" separates pairs of "keys" and "values"
sounds = {"cat": "meow", "dog": "woof"}
dictionaries!
---- animals.py ----
# Creating a dictionary. Note the use of "{" and "}"
# The ":" separates pairs of "keys" and "values"
sounds = {"cat": "meow", "dog": "woof"}
Creating a dictionary:
var = { key-1: value-1, key-2: value-2 … }
keys: Can be strings or numbers (integers, floats).
(or even tuples!)
values: Can be any valid python object
dictionaries!
---- animals.py ----
# Creating a dictionary. Note the use of "{" and "}"
# The ":" separates pairs of "keys" and "values"
sounds = {"cat": "meow", "dog": "woof"}
# using the key to find a value
print sounds["cat"]
# adding and changing an element
sounds["cow"] = "quack"
print sounds
# keys can be strings, ints, floats, or even tuples
sounds[5] = "highfive!"
print sounds
# keys can be strings, ints, floats, or even tuples
sounds[13] = ["llama", 8, "potato"]
print sounds
Creating a dictionary:
var = { key-1: value-1, key-2: value-2 … }
keys: Can be strings or numbers (integers, floats).
(or even tuples!)
values: Can be any valid python object
dictionaries!
---- animals.py ----
# Creating a dictionary. Note the use of "{" and "}"
# The ":" separates pairs of "keys" and "values"
sounds = {"cat": "meow", "dog": "woof"}
# using the key to find a value
print sounds["cat"]
# adding and changing an element
sounds["cow"] = "quack"
print sounds
# keys can be strings, ints, floats, or even tuples
sounds[5] = "highfive!"
print sounds
# keys can be strings, ints, floats, or even tuples
sounds[13] = ["llama", 8, "potato"]
print sounds
Creating a dictionary:
var = { key-1: value-1, key-2: value-2 … }
keys: Can be strings or numbers (integers, floats).
(or even tuples!)
values: Can be any valid python object
dictionaries!
---- animals.py ----
# Creating a dictionary. Note the use of "{" and "}"
# The ":" separates pairs of "keys" and "values"
sounds = {"cat": "meow", "dog": "woof"}
# using the key to find a value
print sounds["cat"]
# adding and changing an element
sounds["cow"] = "quack"
print sounds
# keys can be strings, ints, floats, or even tuples
sounds[5] = "highfive!"
print sounds
# keys can be strings, ints, floats, or even tuples
sounds[13] = ["llama", 8, "potato"]
print sounds
Creating a dictionary:
var = { key-1: value-1, key-2: value-2 … }
keys: Can be strings or numbers (integers, floats).
(or even tuples!)
values: Can be any valid python object
dictionaries are not ordered!
dictionaries!
---- animals.py (cont) ----
# updating an existing dictionary
jungle = {"tiger": "roar", "elephant": "fwaaaap"}
sounds.update(jungle)
print sounds
# accessing keys and values
print sounds.keys()
vals = sounds.value()
print vals
print type(vals)
print sounds.items()
# deleting an entry
print sounds
del sounds["tiger"]
print sounds
# oh yeah.. the len of a dict:
print len(sounds)
Dictionary methods:
mydict.method()
Adding one dictionary to another:
.update(dict)
Accessing keys/values:
.keys()
.values()
.items()
Not methods, but useful too:
len(dict)
del dict[‘key’]
copying dictionaries
---- file contents ----
# making a copy of a dictionary:
dict1 = {1: 2, 3: 12}
dict2 = dict1
dict3 = dict1.copy()
dict1["extra"] = "things"
print dict1
print dict2
print dict3
"=" does not copy a dict!
dict2 = dict1 ← are the same dict
… use:
dict2 = d.copy()
loops + dictionaries!
---- animals.py (cont) ----
sounds = {"cat": "meow", "dog": "woof", "tiger": "roar", "elephant": "fwaaaap"}
# looping over all keys
keys = sounds.keys()
for key in keys:
print “Looping to animal:”, key
loops + dictionaries!
---- animals.py (cont) ----
sounds = {"cat": "meow", "dog": "woof", "tiger": "roar", "elephant": "fwaaaap"}
# looping over all keys
keys = sounds.keys()
for key in keys:
print “Looping to animal:”, key
# looping over all values
values = sounds.values()
for val in values:
print “A noise is:”, val
# looping over all keys (again)
for key in sounds.keys():
print “The”, key, “says:” sound[key]
# looping over all key/value pairs
for key, value in sounds.items():
print “The”, key, “says:” value
Dictionaries in loops:
for key in mydict.keys():
Loop over keys
for value in mydict.values():
Loop over values
for key, value in mydict.items():
Loop over key/value pairs
for key in mydict:
Shorthand to loop over keys
loops + dictionaries!
---- animals.py (cont) ----
sounds = {"cat": "meow", "dog": "woof", "tiger": "roar", "elephant": "fwaaaap"}
# checking if a key exists:
if “cat” in sounds:
print “Cat is in sounds.”
# by default, this only works for keys
if “meow” in sounds:
print “Meow is in sounds”
else:
print “Meow is NOT in sounds”
# if we need to check values, use values()
if “meow” in sounds.values:
print “Meow is in sounds (a value)”
else:
print “Meow is NOT in sounds (values)”
Dictionaries in loops:
if key in mydict:
check if key is in the dictionary
1. Write a script that prints the song.
Animal Orchestra:
# you should be able to copy-paste this :)
sounds = {"cat": "meow", "dog": "woof", "squirrel": "braaaap"}
song = ["dog", "cat", "dog", "squirrel", "dog", "cat", "dog", "squirrel", "dog", "squirrel",]
1. Write a script that prints the song.
2. Elvis (the squirrel) has left the building! Modify the script to write the song as
before, but leave an empty space when Elvis’ part should have been (use key in
dict).
Animal Orchestra:
# you should be able to copy-paste this :)
sounds = {"cat": "meow", "dog": "woof", "squirrel": "braaaap"}
song = ["dog", "cat", "dog", "squirrel", "dog", "cat", "dog", "squirrel", "dog", "squirrel",]
1. Write a script that prints the song.
2. Elvis (the squirrel) has left the building! Modify the script to write the song as
before, but leave an empty space when Elvis’ part should have been (use key in
dict).
3. The replacement has arrived! Prompt the user for the sound that the new squirrel
names. Update the dictionary to reflect these changes, and write the new song.
Animal Orchestra:
# you should be able to copy-paste this :)
sounds = {"cat": "meow", "dog": "woof", "squirrel": "braaaap"}
song = ["dog", "cat", "dog", "squirrel", "dog", "cat", "dog", "squirrel", "dog", "squirrel",]

More Related Content

What's hot

Intro to Python
Intro to PythonIntro to Python
Intro to Python
OSU Open Source Lab
 
Python - Lecture 3
Python - Lecture 3Python - Lecture 3
Python - Lecture 3
Ravi Kiran Khareedi
 
1 the ruby way
1   the ruby way1   the ruby way
1 the ruby way
Luis Doubrava
 
Palestra sobre Collections com Python
Palestra sobre Collections com PythonPalestra sobre Collections com Python
Palestra sobre Collections com Python
pugpe
 
Pa1 session 3_slides
Pa1 session 3_slidesPa1 session 3_slides
Pa1 session 3_slides
aiclub_slides
 
03 Php Array String Functions
03 Php Array String Functions03 Php Array String Functions
03 Php Array String Functions
Geshan Manandhar
 
Php array
Php arrayPhp array
Php array
Core Lee
 
Python 101 1
Python 101   1Python 101   1
Python 101 1
Iccha Sethi
 
ScotRuby - Dark side of ruby
ScotRuby - Dark side of rubyScotRuby - Dark side of ruby
ScotRuby - Dark side of ruby
Gautam Rege
 
Php Using Arrays
Php Using ArraysPhp Using Arrays
Php Using Arrays
mussawir20
 
Php array
Php arrayPhp array
Php array
Nikul Shah
 
Functional Programming & Event Sourcing - a pair made in heaven
Functional Programming & Event Sourcing - a pair made in heavenFunctional Programming & Event Sourcing - a pair made in heaven
Functional Programming & Event Sourcing - a pair made in heaven
Pawel Szulc
 
Arrays in PHP
Arrays in PHPArrays in PHP
Getting to know Arel
Getting to know ArelGetting to know Arel
Getting to know Arel
Ray Zane
 
Learning How To Use Jquery #5
Learning How To Use Jquery #5Learning How To Use Jquery #5
Learning How To Use Jquery #5
Takahiro Yoshimura
 
An (Inaccurate) Introduction to Python
An (Inaccurate) Introduction to PythonAn (Inaccurate) Introduction to Python
An (Inaccurate) Introduction to Python
Nicholas Tollervey
 
Class 4 - PHP Arrays
Class 4 - PHP ArraysClass 4 - PHP Arrays
Class 4 - PHP Arrays
Ahmed Swilam
 
dotSwift 2016 : Beyond Crusty - Real-World Protocols
dotSwift 2016 : Beyond Crusty - Real-World ProtocolsdotSwift 2016 : Beyond Crusty - Real-World Protocols
dotSwift 2016 : Beyond Crusty - Real-World Protocols
Rob Napier
 
PLOTCON NYC: Behind Every Great Plot There's a Great Deal of Wrangling
PLOTCON NYC: Behind Every Great Plot There's a Great Deal of WranglingPLOTCON NYC: Behind Every Great Plot There's a Great Deal of Wrangling
PLOTCON NYC: Behind Every Great Plot There's a Great Deal of Wrangling
Plotly
 
[1062BPY12001] Data analysis with R / week 4
[1062BPY12001] Data analysis with R / week 4[1062BPY12001] Data analysis with R / week 4
[1062BPY12001] Data analysis with R / week 4
Kevin Chun-Hsien Hsu
 

What's hot (20)

Intro to Python
Intro to PythonIntro to Python
Intro to Python
 
Python - Lecture 3
Python - Lecture 3Python - Lecture 3
Python - Lecture 3
 
1 the ruby way
1   the ruby way1   the ruby way
1 the ruby way
 
Palestra sobre Collections com Python
Palestra sobre Collections com PythonPalestra sobre Collections com Python
Palestra sobre Collections com Python
 
Pa1 session 3_slides
Pa1 session 3_slidesPa1 session 3_slides
Pa1 session 3_slides
 
03 Php Array String Functions
03 Php Array String Functions03 Php Array String Functions
03 Php Array String Functions
 
Php array
Php arrayPhp array
Php array
 
Python 101 1
Python 101   1Python 101   1
Python 101 1
 
ScotRuby - Dark side of ruby
ScotRuby - Dark side of rubyScotRuby - Dark side of ruby
ScotRuby - Dark side of ruby
 
Php Using Arrays
Php Using ArraysPhp Using Arrays
Php Using Arrays
 
Php array
Php arrayPhp array
Php array
 
Functional Programming & Event Sourcing - a pair made in heaven
Functional Programming & Event Sourcing - a pair made in heavenFunctional Programming & Event Sourcing - a pair made in heaven
Functional Programming & Event Sourcing - a pair made in heaven
 
Arrays in PHP
Arrays in PHPArrays in PHP
Arrays in PHP
 
Getting to know Arel
Getting to know ArelGetting to know Arel
Getting to know Arel
 
Learning How To Use Jquery #5
Learning How To Use Jquery #5Learning How To Use Jquery #5
Learning How To Use Jquery #5
 
An (Inaccurate) Introduction to Python
An (Inaccurate) Introduction to PythonAn (Inaccurate) Introduction to Python
An (Inaccurate) Introduction to Python
 
Class 4 - PHP Arrays
Class 4 - PHP ArraysClass 4 - PHP Arrays
Class 4 - PHP Arrays
 
dotSwift 2016 : Beyond Crusty - Real-World Protocols
dotSwift 2016 : Beyond Crusty - Real-World ProtocolsdotSwift 2016 : Beyond Crusty - Real-World Protocols
dotSwift 2016 : Beyond Crusty - Real-World Protocols
 
PLOTCON NYC: Behind Every Great Plot There's a Great Deal of Wrangling
PLOTCON NYC: Behind Every Great Plot There's a Great Deal of WranglingPLOTCON NYC: Behind Every Great Plot There's a Great Deal of Wrangling
PLOTCON NYC: Behind Every Great Plot There's a Great Deal of Wrangling
 
[1062BPY12001] Data analysis with R / week 4
[1062BPY12001] Data analysis with R / week 4[1062BPY12001] Data analysis with R / week 4
[1062BPY12001] Data analysis with R / week 4
 

Viewers also liked

Slicing
SlicingSlicing
Tuples
TuplesTuples
Python Workshop Part 2. LUG Maniapl
Python Workshop Part 2. LUG ManiaplPython Workshop Part 2. LUG Maniapl
Python Workshop Part 2. LUG Maniapl
Ankur Shrivastava
 
Dictionaries in Python
Dictionaries in PythonDictionaries in Python
Lists
ListsLists
Programming with Python
Programming with PythonProgramming with Python
Programming with Python
Rasan Samarasinghe
 

Viewers also liked (6)

Slicing
SlicingSlicing
Slicing
 
Tuples
TuplesTuples
Tuples
 
Python Workshop Part 2. LUG Maniapl
Python Workshop Part 2. LUG ManiaplPython Workshop Part 2. LUG Maniapl
Python Workshop Part 2. LUG Maniapl
 
Dictionaries in Python
Dictionaries in PythonDictionaries in Python
Dictionaries in Python
 
Lists
ListsLists
Lists
 
Programming with Python
Programming with PythonProgramming with Python
Programming with Python
 

Similar to Class 6: Lists & dictionaries

Class 5: If, while & lists
Class 5: If, while & listsClass 5: If, while & lists
Class 5: If, while & lists
Marc Gouw
 
第二讲 Python基礎
第二讲 Python基礎第二讲 Python基礎
第二讲 Python基礎
juzihua1102
 
第二讲 预备-Python基礎
第二讲 预备-Python基礎第二讲 预备-Python基礎
第二讲 预备-Python基礎
anzhong70
 
Brixton Library Technology Initiative
Brixton Library Technology InitiativeBrixton Library Technology Initiative
Brixton Library Technology Initiative
Basil Bibi
 
Class 3: if/else
Class 3: if/elseClass 3: if/else
Class 3: if/else
Marc Gouw
 
Python Workshop
Python  Workshop Python  Workshop
Python Workshop
Assem CHELLI
 
Python Basic
Python BasicPython Basic
Python Basic
Adityamelia Permana
 
CoderDojo: Intermediate Python programming course
CoderDojo: Intermediate Python programming courseCoderDojo: Intermediate Python programming course
CoderDojo: Intermediate Python programming course
Alexander Galkin
 
P3 2018 python_regexes
P3 2018 python_regexesP3 2018 python_regexes
P3 2018 python_regexes
Prof. Wim Van Criekinge
 
Python Variable Types, List, Tuple, Dictionary
Python Variable Types, List, Tuple, DictionaryPython Variable Types, List, Tuple, Dictionary
Python Variable Types, List, Tuple, Dictionary
Soba Arjun
 
1. python
1. python1. python
1. python
PRASHANT OJHA
 
Python cheatsheet for beginners
Python cheatsheet for beginnersPython cheatsheet for beginners
Python cheatsheet for beginners
Lahore Garrison University
 
Beginners python cheat sheet - Basic knowledge
Beginners python cheat sheet - Basic knowledge Beginners python cheat sheet - Basic knowledge
Beginners python cheat sheet - Basic knowledge
O T
 
Python Workshop - Learn Python the Hard Way
Python Workshop - Learn Python the Hard WayPython Workshop - Learn Python the Hard Way
Python Workshop - Learn Python the Hard Way
Utkarsh Sengar
 
Python PCEP Tuples and Dictionaries
Python PCEP Tuples and DictionariesPython PCEP Tuples and Dictionaries
Python PCEP Tuples and Dictionaries
IHTMINSTITUTE
 
Python PCEP Tuples and Dictionaries
Python PCEP Tuples and DictionariesPython PCEP Tuples and Dictionaries
Python PCEP Tuples and Dictionaries
IHTMINSTITUTE
 
Python Programming for basic beginners.pptx
Python Programming for basic beginners.pptxPython Programming for basic beginners.pptx
Python Programming for basic beginners.pptx
mohitesoham12
 
Python tutorial
Python tutorialPython tutorial
Python tutorial
nazzf
 
Python tutorial
Python tutorialPython tutorial
Python tutorial
Shani729
 
Introduction to Python
Introduction to PythonIntroduction to Python
Introduction to Python
UC San Diego
 

Similar to Class 6: Lists & dictionaries (20)

Class 5: If, while & lists
Class 5: If, while & listsClass 5: If, while & lists
Class 5: If, while & lists
 
第二讲 Python基礎
第二讲 Python基礎第二讲 Python基礎
第二讲 Python基礎
 
第二讲 预备-Python基礎
第二讲 预备-Python基礎第二讲 预备-Python基礎
第二讲 预备-Python基礎
 
Brixton Library Technology Initiative
Brixton Library Technology InitiativeBrixton Library Technology Initiative
Brixton Library Technology Initiative
 
Class 3: if/else
Class 3: if/elseClass 3: if/else
Class 3: if/else
 
Python Workshop
Python  Workshop Python  Workshop
Python Workshop
 
Python Basic
Python BasicPython Basic
Python Basic
 
CoderDojo: Intermediate Python programming course
CoderDojo: Intermediate Python programming courseCoderDojo: Intermediate Python programming course
CoderDojo: Intermediate Python programming course
 
P3 2018 python_regexes
P3 2018 python_regexesP3 2018 python_regexes
P3 2018 python_regexes
 
Python Variable Types, List, Tuple, Dictionary
Python Variable Types, List, Tuple, DictionaryPython Variable Types, List, Tuple, Dictionary
Python Variable Types, List, Tuple, Dictionary
 
1. python
1. python1. python
1. python
 
Python cheatsheet for beginners
Python cheatsheet for beginnersPython cheatsheet for beginners
Python cheatsheet for beginners
 
Beginners python cheat sheet - Basic knowledge
Beginners python cheat sheet - Basic knowledge Beginners python cheat sheet - Basic knowledge
Beginners python cheat sheet - Basic knowledge
 
Python Workshop - Learn Python the Hard Way
Python Workshop - Learn Python the Hard WayPython Workshop - Learn Python the Hard Way
Python Workshop - Learn Python the Hard Way
 
Python PCEP Tuples and Dictionaries
Python PCEP Tuples and DictionariesPython PCEP Tuples and Dictionaries
Python PCEP Tuples and Dictionaries
 
Python PCEP Tuples and Dictionaries
Python PCEP Tuples and DictionariesPython PCEP Tuples and Dictionaries
Python PCEP Tuples and Dictionaries
 
Python Programming for basic beginners.pptx
Python Programming for basic beginners.pptxPython Programming for basic beginners.pptx
Python Programming for basic beginners.pptx
 
Python tutorial
Python tutorialPython tutorial
Python tutorial
 
Python tutorial
Python tutorialPython tutorial
Python tutorial
 
Introduction to Python
Introduction to PythonIntroduction to Python
Introduction to Python
 

More from Marc Gouw

Class 7b: Files & File I/O
Class 7b: Files & File I/OClass 7b: Files & File I/O
Class 7b: Files & File I/O
Marc Gouw
 
Class 2: Welcome part 2
Class 2: Welcome part 2Class 2: Welcome part 2
Class 2: Welcome part 2
Marc Gouw
 
Class 4: For and while
Class 4: For and whileClass 4: For and while
Class 4: For and while
Marc Gouw
 
Class 8b: Numpy & Matplotlib
Class 8b: Numpy & MatplotlibClass 8b: Numpy & Matplotlib
Class 8b: Numpy & Matplotlib
Marc Gouw
 
Class 7a: Functions
Class 7a: FunctionsClass 7a: Functions
Class 7a: Functions
Marc Gouw
 
Class 8a: Modules and imports
Class 8a: Modules and importsClass 8a: Modules and imports
Class 8a: Modules and imports
Marc Gouw
 
Class 1: Welcome to programming
Class 1: Welcome to programmingClass 1: Welcome to programming
Class 1: Welcome to programming
Marc Gouw
 

More from Marc Gouw (7)

Class 7b: Files & File I/O
Class 7b: Files & File I/OClass 7b: Files & File I/O
Class 7b: Files & File I/O
 
Class 2: Welcome part 2
Class 2: Welcome part 2Class 2: Welcome part 2
Class 2: Welcome part 2
 
Class 4: For and while
Class 4: For and whileClass 4: For and while
Class 4: For and while
 
Class 8b: Numpy & Matplotlib
Class 8b: Numpy & MatplotlibClass 8b: Numpy & Matplotlib
Class 8b: Numpy & Matplotlib
 
Class 7a: Functions
Class 7a: FunctionsClass 7a: Functions
Class 7a: Functions
 
Class 8a: Modules and imports
Class 8a: Modules and importsClass 8a: Modules and imports
Class 8a: Modules and imports
 
Class 1: Welcome to programming
Class 1: Welcome to programmingClass 1: Welcome to programming
Class 1: Welcome to programming
 

Recently uploaded

Randomised Optimisation Algorithms in DAPHNE
Randomised Optimisation Algorithms in DAPHNERandomised Optimisation Algorithms in DAPHNE
Randomised Optimisation Algorithms in DAPHNE
University of Maribor
 
Nucleophilic Addition of carbonyl compounds.pptx
Nucleophilic Addition of carbonyl  compounds.pptxNucleophilic Addition of carbonyl  compounds.pptx
Nucleophilic Addition of carbonyl compounds.pptx
SSR02
 
THEMATIC APPERCEPTION TEST(TAT) cognitive abilities, creativity, and critic...
THEMATIC  APPERCEPTION  TEST(TAT) cognitive abilities, creativity, and critic...THEMATIC  APPERCEPTION  TEST(TAT) cognitive abilities, creativity, and critic...
THEMATIC APPERCEPTION TEST(TAT) cognitive abilities, creativity, and critic...
Abdul Wali Khan University Mardan,kP,Pakistan
 
mô tả các thí nghiệm về đánh giá tác động dòng khí hóa sau đốt
mô tả các thí nghiệm về đánh giá tác động dòng khí hóa sau đốtmô tả các thí nghiệm về đánh giá tác động dòng khí hóa sau đốt
mô tả các thí nghiệm về đánh giá tác động dòng khí hóa sau đốt
HongcNguyn6
 
NuGOweek 2024 Ghent programme overview flyer
NuGOweek 2024 Ghent programme overview flyerNuGOweek 2024 Ghent programme overview flyer
NuGOweek 2024 Ghent programme overview flyer
pablovgd
 
What is greenhouse gasses and how many gasses are there to affect the Earth.
What is greenhouse gasses and how many gasses are there to affect the Earth.What is greenhouse gasses and how many gasses are there to affect the Earth.
What is greenhouse gasses and how many gasses are there to affect the Earth.
moosaasad1975
 
原版制作(carleton毕业证书)卡尔顿大学毕业证硕士文凭原版一模一样
原版制作(carleton毕业证书)卡尔顿大学毕业证硕士文凭原版一模一样原版制作(carleton毕业证书)卡尔顿大学毕业证硕士文凭原版一模一样
原版制作(carleton毕业证书)卡尔顿大学毕业证硕士文凭原版一模一样
yqqaatn0
 
Chapter 12 - climate change and the energy crisis
Chapter 12 - climate change and the energy crisisChapter 12 - climate change and the energy crisis
Chapter 12 - climate change and the energy crisis
tonzsalvador2222
 
The debris of the ‘last major merger’ is dynamically young
The debris of the ‘last major merger’ is dynamically youngThe debris of the ‘last major merger’ is dynamically young
The debris of the ‘last major merger’ is dynamically young
Sérgio Sacani
 
SAR of Medicinal Chemistry 1st by dk.pdf
SAR of Medicinal Chemistry 1st by dk.pdfSAR of Medicinal Chemistry 1st by dk.pdf
SAR of Medicinal Chemistry 1st by dk.pdf
KrushnaDarade1
 
Shallowest Oil Discovery of Turkiye.pptx
Shallowest Oil Discovery of Turkiye.pptxShallowest Oil Discovery of Turkiye.pptx
Shallowest Oil Discovery of Turkiye.pptx
Gokturk Mehmet Dilci
 
Unlocking the mysteries of reproduction: Exploring fecundity and gonadosomati...
Unlocking the mysteries of reproduction: Exploring fecundity and gonadosomati...Unlocking the mysteries of reproduction: Exploring fecundity and gonadosomati...
Unlocking the mysteries of reproduction: Exploring fecundity and gonadosomati...
AbdullaAlAsif1
 
ANAMOLOUS SECONDARY GROWTH IN DICOT ROOTS.pptx
ANAMOLOUS SECONDARY GROWTH IN DICOT ROOTS.pptxANAMOLOUS SECONDARY GROWTH IN DICOT ROOTS.pptx
ANAMOLOUS SECONDARY GROWTH IN DICOT ROOTS.pptx
RASHMI M G
 
The binding of cosmological structures by massless topological defects
The binding of cosmological structures by massless topological defectsThe binding of cosmological structures by massless topological defects
The binding of cosmological structures by massless topological defects
Sérgio Sacani
 
Sharlene Leurig - Enabling Onsite Water Use with Net Zero Water
Sharlene Leurig - Enabling Onsite Water Use with Net Zero WaterSharlene Leurig - Enabling Onsite Water Use with Net Zero Water
Sharlene Leurig - Enabling Onsite Water Use with Net Zero Water
Texas Alliance of Groundwater Districts
 
Topic: SICKLE CELL DISEASE IN CHILDREN-3.pdf
Topic: SICKLE CELL DISEASE IN CHILDREN-3.pdfTopic: SICKLE CELL DISEASE IN CHILDREN-3.pdf
Topic: SICKLE CELL DISEASE IN CHILDREN-3.pdf
TinyAnderson
 
Remote Sensing and Computational, Evolutionary, Supercomputing, and Intellige...
Remote Sensing and Computational, Evolutionary, Supercomputing, and Intellige...Remote Sensing and Computational, Evolutionary, Supercomputing, and Intellige...
Remote Sensing and Computational, Evolutionary, Supercomputing, and Intellige...
University of Maribor
 
Comparing Evolved Extractive Text Summary Scores of Bidirectional Encoder Rep...
Comparing Evolved Extractive Text Summary Scores of Bidirectional Encoder Rep...Comparing Evolved Extractive Text Summary Scores of Bidirectional Encoder Rep...
Comparing Evolved Extractive Text Summary Scores of Bidirectional Encoder Rep...
University of Maribor
 
8.Isolation of pure cultures and preservation of cultures.pdf
8.Isolation of pure cultures and preservation of cultures.pdf8.Isolation of pure cultures and preservation of cultures.pdf
8.Isolation of pure cultures and preservation of cultures.pdf
by6843629
 
ESR spectroscopy in liquid food and beverages.pptx
ESR spectroscopy in liquid food and beverages.pptxESR spectroscopy in liquid food and beverages.pptx
ESR spectroscopy in liquid food and beverages.pptx
PRIYANKA PATEL
 

Recently uploaded (20)

Randomised Optimisation Algorithms in DAPHNE
Randomised Optimisation Algorithms in DAPHNERandomised Optimisation Algorithms in DAPHNE
Randomised Optimisation Algorithms in DAPHNE
 
Nucleophilic Addition of carbonyl compounds.pptx
Nucleophilic Addition of carbonyl  compounds.pptxNucleophilic Addition of carbonyl  compounds.pptx
Nucleophilic Addition of carbonyl compounds.pptx
 
THEMATIC APPERCEPTION TEST(TAT) cognitive abilities, creativity, and critic...
THEMATIC  APPERCEPTION  TEST(TAT) cognitive abilities, creativity, and critic...THEMATIC  APPERCEPTION  TEST(TAT) cognitive abilities, creativity, and critic...
THEMATIC APPERCEPTION TEST(TAT) cognitive abilities, creativity, and critic...
 
mô tả các thí nghiệm về đánh giá tác động dòng khí hóa sau đốt
mô tả các thí nghiệm về đánh giá tác động dòng khí hóa sau đốtmô tả các thí nghiệm về đánh giá tác động dòng khí hóa sau đốt
mô tả các thí nghiệm về đánh giá tác động dòng khí hóa sau đốt
 
NuGOweek 2024 Ghent programme overview flyer
NuGOweek 2024 Ghent programme overview flyerNuGOweek 2024 Ghent programme overview flyer
NuGOweek 2024 Ghent programme overview flyer
 
What is greenhouse gasses and how many gasses are there to affect the Earth.
What is greenhouse gasses and how many gasses are there to affect the Earth.What is greenhouse gasses and how many gasses are there to affect the Earth.
What is greenhouse gasses and how many gasses are there to affect the Earth.
 
原版制作(carleton毕业证书)卡尔顿大学毕业证硕士文凭原版一模一样
原版制作(carleton毕业证书)卡尔顿大学毕业证硕士文凭原版一模一样原版制作(carleton毕业证书)卡尔顿大学毕业证硕士文凭原版一模一样
原版制作(carleton毕业证书)卡尔顿大学毕业证硕士文凭原版一模一样
 
Chapter 12 - climate change and the energy crisis
Chapter 12 - climate change and the energy crisisChapter 12 - climate change and the energy crisis
Chapter 12 - climate change and the energy crisis
 
The debris of the ‘last major merger’ is dynamically young
The debris of the ‘last major merger’ is dynamically youngThe debris of the ‘last major merger’ is dynamically young
The debris of the ‘last major merger’ is dynamically young
 
SAR of Medicinal Chemistry 1st by dk.pdf
SAR of Medicinal Chemistry 1st by dk.pdfSAR of Medicinal Chemistry 1st by dk.pdf
SAR of Medicinal Chemistry 1st by dk.pdf
 
Shallowest Oil Discovery of Turkiye.pptx
Shallowest Oil Discovery of Turkiye.pptxShallowest Oil Discovery of Turkiye.pptx
Shallowest Oil Discovery of Turkiye.pptx
 
Unlocking the mysteries of reproduction: Exploring fecundity and gonadosomati...
Unlocking the mysteries of reproduction: Exploring fecundity and gonadosomati...Unlocking the mysteries of reproduction: Exploring fecundity and gonadosomati...
Unlocking the mysteries of reproduction: Exploring fecundity and gonadosomati...
 
ANAMOLOUS SECONDARY GROWTH IN DICOT ROOTS.pptx
ANAMOLOUS SECONDARY GROWTH IN DICOT ROOTS.pptxANAMOLOUS SECONDARY GROWTH IN DICOT ROOTS.pptx
ANAMOLOUS SECONDARY GROWTH IN DICOT ROOTS.pptx
 
The binding of cosmological structures by massless topological defects
The binding of cosmological structures by massless topological defectsThe binding of cosmological structures by massless topological defects
The binding of cosmological structures by massless topological defects
 
Sharlene Leurig - Enabling Onsite Water Use with Net Zero Water
Sharlene Leurig - Enabling Onsite Water Use with Net Zero WaterSharlene Leurig - Enabling Onsite Water Use with Net Zero Water
Sharlene Leurig - Enabling Onsite Water Use with Net Zero Water
 
Topic: SICKLE CELL DISEASE IN CHILDREN-3.pdf
Topic: SICKLE CELL DISEASE IN CHILDREN-3.pdfTopic: SICKLE CELL DISEASE IN CHILDREN-3.pdf
Topic: SICKLE CELL DISEASE IN CHILDREN-3.pdf
 
Remote Sensing and Computational, Evolutionary, Supercomputing, and Intellige...
Remote Sensing and Computational, Evolutionary, Supercomputing, and Intellige...Remote Sensing and Computational, Evolutionary, Supercomputing, and Intellige...
Remote Sensing and Computational, Evolutionary, Supercomputing, and Intellige...
 
Comparing Evolved Extractive Text Summary Scores of Bidirectional Encoder Rep...
Comparing Evolved Extractive Text Summary Scores of Bidirectional Encoder Rep...Comparing Evolved Extractive Text Summary Scores of Bidirectional Encoder Rep...
Comparing Evolved Extractive Text Summary Scores of Bidirectional Encoder Rep...
 
8.Isolation of pure cultures and preservation of cultures.pdf
8.Isolation of pure cultures and preservation of cultures.pdf8.Isolation of pure cultures and preservation of cultures.pdf
8.Isolation of pure cultures and preservation of cultures.pdf
 
ESR spectroscopy in liquid food and beverages.pptx
ESR spectroscopy in liquid food and beverages.pptxESR spectroscopy in liquid food and beverages.pptx
ESR spectroscopy in liquid food and beverages.pptx
 

Class 6: Lists & dictionaries

  • 2. The plan! Basics: data types (and operations & calculations) Basics: conditionals & iteration Basics: lists, tuples, dictionaries Basics: writing functions Reading & writing files: opening, parsing & formats Working with numbers: numpy & scipy Making plots: matplotlib & pylab … if you guys want more after all of that … Writing better code: functions, pep8, classes Working with numbers: Numpy & Scipy (advanced) Other modules: Pandas & Scikit-learn Interactive notebooks: ipython & jupyter Advanced topics: virtual environments & version control
  • 3. data types for multiple things... lists [ 1, 2, 3, 100, 99 , 50] strings "wait, we already know these!" tuples (10, 11, 12, 100, 90, 80) dictionaries {"name": "Bob", "age": 33}
  • 4. lists # define a list: mylist = [5, 3, 1, "a", [12, 14, 16],] # indexing and slicing: print mylist[2] print mylist[:4] # changing elements mylist[2] = 300 print mylist Using an existing list with methods: mylist.method() Finding things: .index(element) ← first only .count(element) Removing things: .pop(<pos>) ← returns element .remove(element) Adding things: .append(element) .insert(pos, element) .extend(newlist) also useful: len(list) copying lists: list2 = list(list1)
  • 5. lists, loops and conditionals ---- somefile.py ---- # lets take a close look at "range": a = range(10) print type(a) # (note: different in python 3)
  • 6. lists, loops and conditionals ---- somefile.py ---- # lets take a close look at "range": a = range(10) print type(a) # (note: different in python 3) # using lists in loops: somelist = [1, 2, "a", "b", "hello", 3.0, 99] for element in somelist: print element, "is of type:", type(element)
  • 7. lists, loops and conditionals ---- somefile.py ---- # lets take a close look at "range": a = range(10) print type(a) # (note: different in python 3) # using lists in loops: somelist = [1, 2, "a", "b", "hello", 3.0, 99] for element in somelist: print element, "is of type:", type(element) # using lists in conditionals: if "a" in somelist: print "a is in the list" Using in with lists: for var in list: do stuff in loop if var in list: do "True" block else: do "False" block
  • 8. lists, loops and conditionals ---- somefile.py ---- # lets take a close look at "range": a = range(10) print type(a) # (note: different in python 3) # using lists in loops: somelist = [1, 2, "a", "b", "hello", 3.0, 99] for element in somelist: print element, "is of type:", type(element) # using lists in conditionals: if "a" in somelist: print "a is in the list" # using lists in tests and conditionals: mylist = [1, 2, "a", "b", "hello", 99] for a in range(100): if a in mylist: print a, "is in the list!" Using in with lists: for var in list: do stuff in loop if var in list: do "True" block else: do "False" block
  • 9. - you can download this from our drive: hamcakes_script - How many ingredients are there in total (in the snack)? - Are there any in the "snack" which are not in "pancakes" or "hamburger"? (add these to the correct list) - By majority vote: is it a pancake or hamburger? hamcake! # you should be able to copy-paste this :) snack = [ "chocolate", "strawberries", "salad", "chocolate", "salad", "cheese", "cream", "cheese", "tomatoes", "bacon", "bacon", "tomatoes", "burger", "onions", "cheese", "banana", "pineapple", "tomatoes", "bacon", "cheese", "burger", "salad", "tomatoes", "onions", "chocolate", "pineapple", "tomatoes", "onions", "salad", "strawberries", "egg", "cheese", "tomatoes", "burger", "bacon", "cream", "sugar", "burger", "ketchup", "salad", "chocolate", "cream", "egg", "sugar", "salad", "pineapple", "bacon", "cheese", "bacon", ] pancake = [ "chocolate", "strawberries", "chocolate", "cream", "pineapple", "sugar",] hamburger = [ "tomatoes", "bacon", "cheese", "burger", "salad", "onions", "egg", ]
  • 10. dictionaries! ---- animals.py ---- # Creating a dictionary. Note the use of "{" and "}" # The ":" separates pairs of "keys" and "values" sounds = {"cat": "meow", "dog": "woof"}
  • 11. dictionaries! ---- animals.py ---- # Creating a dictionary. Note the use of "{" and "}" # The ":" separates pairs of "keys" and "values" sounds = {"cat": "meow", "dog": "woof"} Creating a dictionary: var = { key-1: value-1, key-2: value-2 … } keys: Can be strings or numbers (integers, floats). (or even tuples!) values: Can be any valid python object
  • 12. dictionaries! ---- animals.py ---- # Creating a dictionary. Note the use of "{" and "}" # The ":" separates pairs of "keys" and "values" sounds = {"cat": "meow", "dog": "woof"} # using the key to find a value print sounds["cat"] # adding and changing an element sounds["cow"] = "quack" print sounds # keys can be strings, ints, floats, or even tuples sounds[5] = "highfive!" print sounds # keys can be strings, ints, floats, or even tuples sounds[13] = ["llama", 8, "potato"] print sounds Creating a dictionary: var = { key-1: value-1, key-2: value-2 … } keys: Can be strings or numbers (integers, floats). (or even tuples!) values: Can be any valid python object
  • 13. dictionaries! ---- animals.py ---- # Creating a dictionary. Note the use of "{" and "}" # The ":" separates pairs of "keys" and "values" sounds = {"cat": "meow", "dog": "woof"} # using the key to find a value print sounds["cat"] # adding and changing an element sounds["cow"] = "quack" print sounds # keys can be strings, ints, floats, or even tuples sounds[5] = "highfive!" print sounds # keys can be strings, ints, floats, or even tuples sounds[13] = ["llama", 8, "potato"] print sounds Creating a dictionary: var = { key-1: value-1, key-2: value-2 … } keys: Can be strings or numbers (integers, floats). (or even tuples!) values: Can be any valid python object
  • 14. dictionaries! ---- animals.py ---- # Creating a dictionary. Note the use of "{" and "}" # The ":" separates pairs of "keys" and "values" sounds = {"cat": "meow", "dog": "woof"} # using the key to find a value print sounds["cat"] # adding and changing an element sounds["cow"] = "quack" print sounds # keys can be strings, ints, floats, or even tuples sounds[5] = "highfive!" print sounds # keys can be strings, ints, floats, or even tuples sounds[13] = ["llama", 8, "potato"] print sounds Creating a dictionary: var = { key-1: value-1, key-2: value-2 … } keys: Can be strings or numbers (integers, floats). (or even tuples!) values: Can be any valid python object dictionaries are not ordered!
  • 15. dictionaries! ---- animals.py (cont) ---- # updating an existing dictionary jungle = {"tiger": "roar", "elephant": "fwaaaap"} sounds.update(jungle) print sounds # accessing keys and values print sounds.keys() vals = sounds.value() print vals print type(vals) print sounds.items() # deleting an entry print sounds del sounds["tiger"] print sounds # oh yeah.. the len of a dict: print len(sounds) Dictionary methods: mydict.method() Adding one dictionary to another: .update(dict) Accessing keys/values: .keys() .values() .items() Not methods, but useful too: len(dict) del dict[‘key’]
  • 16. copying dictionaries ---- file contents ---- # making a copy of a dictionary: dict1 = {1: 2, 3: 12} dict2 = dict1 dict3 = dict1.copy() dict1["extra"] = "things" print dict1 print dict2 print dict3 "=" does not copy a dict! dict2 = dict1 ← are the same dict … use: dict2 = d.copy()
  • 17. loops + dictionaries! ---- animals.py (cont) ---- sounds = {"cat": "meow", "dog": "woof", "tiger": "roar", "elephant": "fwaaaap"} # looping over all keys keys = sounds.keys() for key in keys: print “Looping to animal:”, key
  • 18. loops + dictionaries! ---- animals.py (cont) ---- sounds = {"cat": "meow", "dog": "woof", "tiger": "roar", "elephant": "fwaaaap"} # looping over all keys keys = sounds.keys() for key in keys: print “Looping to animal:”, key # looping over all values values = sounds.values() for val in values: print “A noise is:”, val # looping over all keys (again) for key in sounds.keys(): print “The”, key, “says:” sound[key] # looping over all key/value pairs for key, value in sounds.items(): print “The”, key, “says:” value Dictionaries in loops: for key in mydict.keys(): Loop over keys for value in mydict.values(): Loop over values for key, value in mydict.items(): Loop over key/value pairs for key in mydict: Shorthand to loop over keys
  • 19. loops + dictionaries! ---- animals.py (cont) ---- sounds = {"cat": "meow", "dog": "woof", "tiger": "roar", "elephant": "fwaaaap"} # checking if a key exists: if “cat” in sounds: print “Cat is in sounds.” # by default, this only works for keys if “meow” in sounds: print “Meow is in sounds” else: print “Meow is NOT in sounds” # if we need to check values, use values() if “meow” in sounds.values: print “Meow is in sounds (a value)” else: print “Meow is NOT in sounds (values)” Dictionaries in loops: if key in mydict: check if key is in the dictionary
  • 20. 1. Write a script that prints the song. Animal Orchestra: # you should be able to copy-paste this :) sounds = {"cat": "meow", "dog": "woof", "squirrel": "braaaap"} song = ["dog", "cat", "dog", "squirrel", "dog", "cat", "dog", "squirrel", "dog", "squirrel",]
  • 21. 1. Write a script that prints the song. 2. Elvis (the squirrel) has left the building! Modify the script to write the song as before, but leave an empty space when Elvis’ part should have been (use key in dict). Animal Orchestra: # you should be able to copy-paste this :) sounds = {"cat": "meow", "dog": "woof", "squirrel": "braaaap"} song = ["dog", "cat", "dog", "squirrel", "dog", "cat", "dog", "squirrel", "dog", "squirrel",]
  • 22. 1. Write a script that prints the song. 2. Elvis (the squirrel) has left the building! Modify the script to write the song as before, but leave an empty space when Elvis’ part should have been (use key in dict). 3. The replacement has arrived! Prompt the user for the sound that the new squirrel names. Update the dictionary to reflect these changes, and write the new song. Animal Orchestra: # you should be able to copy-paste this :) sounds = {"cat": "meow", "dog": "woof", "squirrel": "braaaap"} song = ["dog", "cat", "dog", "squirrel", "dog", "cat", "dog", "squirrel", "dog", "squirrel",]