The in
keyword checks if
a value is in a list (or any sequence).
if "bananas" in groceries:
print("Watch your step!")
if "bleach" in groceries:
print("Watch what you eat!")
When used inside if conditions, in
expressions return a Boolean (True
/False
).
Method | Description |
---|---|
count(item)
| Returns the number of occurrences of item in the list. If item is not found, returns 0.
|
reverse()
| Reverses the elements of the list in place. |
sort([key=function])
| Sorts the items of the list in place. The optional key argument specifies
a function to compute a comparison key for each item in the list. Otherwise, items are compared based on their values.
|
For more about list methods, seePython.org documentation
These are functions, not methods.
Module | Function | Description |
---|---|---|
Global | min(list, [key=function])
| Returns the minimum value in list . The optional key argument specifies a custom comparator function.
|
Global | max(list, [key=function])
| Returns the maximum value in list . he optional key argument specifies a custom comparator function.
|
random
| choice(list)
| Returns a randomly selected item from list .
|
random
| shuffle(list)
| Shuffles the elements of the list in place. |
For more on built-in functions see Python.org documentation. Functions that work with lists are those that accept an "iterable" as an argument.
Since Python lists can contain any values, an item can itself be a list.
gymnasts = [
["Brittany", 9.15, 9.4, 9.3, 9.2], # gymnasts[0]
["Lea", 9, 8.8, 9.1, 9.5], # gymnasts[1]
["Maya", 9.2, 8.7, 9.2, 8.8] # gymnasts[2]
]
You can think of nested lists like rows in a table:
gymnasts = [
["Brittany", 9.15, 9.4, 9.3, 9.2],
["Lea", 9, 8.8, 9.1, 9.5],
["Maya", 9.2, 8.7, 9.2, 8.8]
]
Access using bracket notation, with more brackets as needed:
gymnasts[0] # ["Brittany", 9.15, 9.4, 9.3, 9.2]
gymnasts[0][0] # "Brittany"
gymnasts[1][0] # "Lea"
gymnasts[1][4] # 9.5
gymnasts[1][5] # ๐ซ IndexError!
gymnasts[3][0] # ๐ซ IndexError!
gymnasts = [
["Brittany", 9.15, 9.4, 9.3, 9.2],
["Lea", 9, 8.8, 9.1, 9.5],
["Maya", 9.2, 8.7, 9.2, 8.8]
]
Modify using bracket notation as well, just like before:
gymnasts[0] = ["Olivia", 8.75, 9.1, 9.6, 9.8]
gymnasts[1][0] = "Leah"
gymnasts[2][4] = 9.8
If we start with...
gymnasts = [
["Brittany", 9.15, 9.4, 9.3, 9.2],
["Lea", 9, 8.8, 9.1, 9.5]
]
We can append another list a few ways:
gymnasts.append(["Maya", 9.2, 8.7, 9.2, 8.8])
gymnast = []
gymnast.append("Maya")
gymnast.append(9.2)
gymnast.append(8.7)
gymnast.append(9.2)
gymnast.append(8.8)
gymnasts.append(gymnast)
gymnasts = [
["Brittany", 9.15, 9.4, 9.3, 9.2],
["Lea", 9, 8.8, 9.1, 9.5],
["Maya", 9.2, 8.7, 9.2, 8.8]
]
Use a nested for-in
loop:
for gymnast in gymnasts:
print(gymnast)
for data in gymnast:
print(data)
Remember what type of data is being stored in the loop variable!
Comma Separated Value (CSV) is a plain text format used to store "tabular" data (aka rows and columns), like from a spreadsheet or database table.
Because CSV is simple and non-proprietary, it's commonly used to exchange data between different applications.
Brittany, 9.15, 9.4, 9.3, 9.2
Lea, 9, 8.8, 9.1, 9.5
Maya, 9.2, 8.7, 9.2, 8.8
We use the Python built in open()
method to open files for reading or writing.
The keyword with
tells Python to automatically close the file when we're finished.
with open('filename') as my_file:
# do something
Python has a built-in CSV module that includes many features used for reading/writing CSV files.
Open a CSV and read its contents (docs at python.org)
# import the csv module
import csv
# open the file
with open('fun_spreadsheet.csv') as my_file:
# load the contents of the CSV file into a variable
csv_reader = csv.reader(my_file)
# CSV is a nested list!
# now we can loop through the rows in the file
for row in csv_reader:
print(row)
A CSV is a list of rows, which are lists of values.
We can use nested for loops to get values from rows and cells.
import csv
with open('fun_spreadsheet.csv') as my_file:
csv_reader = csv.reader(my_file, delimiter=',')
for row in csv_reader:
print(row)
for cell in row:
print(cell)
A tuple is like a list, but immutable: its values cannot be changed after the initialization.
Tuples are enclosed in parentheses (9.99, 7.99, 3.99)
position = (100, 50)
prices = (9.99, 7.99, 3.99)
You can still access items in a tuple:
position = (100, 50)
x = position[1]
y = position[2]
Or iterate through:
total = 0
for price in prices:
total += price
All of these operations will result in an error:
position = (100, 50)
position[0] = 50
position[1] = 10
position.append(10)
When you have list that won't change as your program runs. Tuples are much more memory efficent than lists. Your code will run much faster!
A dict
is a mutable mapping of key-value pairs
states = {
"CA": "California",
"DE": "Delaware",
"NY": "New York",
"TX": "Texas",
"WY": "Wyoming"
}
Dictionaries allow you to access values using a human-readable name ("key") rather than an index number. Dictionaries map very well to JSON!
>>> len(states)
5
>>> "CA" in states
True
>>> "ZZ" in states
False
words = {
"mรกs": "more",
"otro": "other",
"agua": "water"
}
Select a value:
>>> words["otro"]
'other'
>>> first_word = "agua"
>>> words[first_word]
'water'
>>> words["pavo"]
KeyError: pavo
Create an empty dict:
users = {}
Add values:
users["liz"] = "b3stp@ssEvErDontHackMe"
Change values:
users["liz"] = "itsLongerSoItsMoreSecure!!"
>>> users["liz"]
'itsLongerSoItsMoreSecure!!'
spiders = {
"smeringopus": {
"name": "Pale Daddy Long-leg",
"length": 7
},
"holocnemus pluchei": {
"name": "Marbled cellar spider",
"length": (5, 7)
}
}
insects = {"spiders": 8, "centipedes": 100, "bees": 6}
for insect in insects:
print("Key is " + insect)
# ex insects['spiders']
print("Value is " + str(insects[insect]))
What will be the order of items?
8 100 6
Keys are iterated over in the order they are first added.
The .items()
dictionary method returns a list containing a tuple for each key/value pair
insects = {"spiders": 8, "centipedes": 100, "bees": 6}
for key, value in insects.items()
print("Key is " + key)
print("Value is " + str(value))
Python has a built-in CSV module that includes many features used for reading/writing CSV files.
Open a CSV and read its contents
# import the csv module
import csv
# open the file
with open('fun_spreadsheet.csv') as my_file:
# load the contents of the CSV file into a variable
csv_reader = csv.DictReader(my_file)
# CSV is read as a dictionary with column headers as keys!
# now we can loop through the rows in the file
# and get the values from specific columns
for row in csv_reader:
print(row)
Let's re-visit our gradebook exercise...
Python's built-in CSV module also has support for writing files (docs at python.org)
# import the csv module
import csv
my_list = [
["Mon", "Oatmeal", "Salad", "Pasta"],
["Tues", "Waffles", "Soup", "Tacos"],
["Wed", "Cereal", "Sandwich", "Pizza"]
]
# open a new or existing file for writing
with open('fun_spreadsheet.csv', 'w') as my_file:
# prepare the CSV for writing
writer = csv.writer(my_file)
# write data from a list to the CSV file
writer.writerows(my_list)
Let's put it all together in one final exercise!
Hands-on project ideas:
Frameworks like Django and Flask are commonly used to build web apps quickly
Please fill out the GDI feedback survey to help us improve future classes. Thanks!