We use square brackets to create lists.
years = [1998, 2001, 2007]
years
schools = ['cal', 1868, 'cal poly', 1901, 'columbia', 1754]
schools
nums = [2 + 2, 5, 5 - 1]
nums
type([3, 1, 2])
type([])
[3, 1, 2] == [3, 1, 2]
[3, 1, 2] == [3, 1, 2, -4]
len([9, 2.5, 7])
max([9, 2.5, 7])
# Earliest in dictionary
min(['hello', 'hi', 'abbey'])
# TypeError!
min(['hello', 2.5, 'abbey'])
sum([9, 2.5, 7])
[1, 2] + [3, 4] * 2
groceries = ['eggs', 'milk']
groceries
groceries.append('bread')
groceries
3 in [3, 1, 'dog']
10 not in [3, 1, 'dog']
not 10 in [3, 1, 'dog']
[3, 1] in [3, 1, 'dog']
nums = [3, 1, 'dog', -9.5, 'berk']
nums[0]
nums[3]
nums[5]
nums = [3, 1, 'dog', -9.5, 'berk']
nums[1:3]
nums[0:4]
# If you don't include 'start',
# the slice starts at the
# beginning of the list
nums[:4]
# If you don't include 'stop',
# the slice goes until the
# end of the list
nums[2:]
nums = [3, 1, 'dog', -9.5, 'berk']
nums[len(nums) - 1]
nums[-1]
nums[-3]
nums[-3:]
def square_all(vals):
output = []
i = 0
while i < len(vals):
val_squared = vals[i] ** 2
output.append(val_squared)
i += 1
return output
square_all([1, 10, 3, 4])
.index
tells us the position of an element in a list – if it is in the list.
[9, 8, 14, -1].index(14)
[9, 8, 14, -1].index(15)
# Two occurrences of 2
# Gives index of first one
[1, 2, 4, 2, 4].index(2)
[1, 2, 4, 2, 4].count(2)
def next_day(day):
week = ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday']
curr = week.index(day)
return week[(curr + 1) % 7]
next_day('Wednesday')
next_day('Saturday')
university = 'uc berkeley'
list(university)
university[3:7]
university[1]
university[-8:]
# Weird slicing that can be used
# to reverse a string or list
university[::-1]
'alfalfa'.find('f')
'alfalfa'.rfind('a')
'alfalfa'.find('b')
'alfalfa'.index('b')
test_list = [8, 0, 2, 4]
test_string = 'zebra'
test_list[1] = 99
test_list
test_string[1] = 'f'
test_string[:1] + 'f' + test_string[2:]
Let's use data about survivors of the Titanic, downloaded from here.
from datascience import *
table = Table.read_table('data/titanic.csv').select(['Name', 'Age', 'Sex', 'Fare', 'Survived'])
table
Soon, we will learn how to load in data like the above and extract columns as lists. But for now, just run the following cell.
names = list(table.column('Name'))
ages = list(table.column('Age'))
survived = list(table.column('Survived'))
ages[:5]
names[:5]
100 * sum(survived) / len(survived)