Вы находитесь на странице: 1из 38

Lists, Tuples, and

Dictionaries
CS 111: Computer Science for Scientists
Making a sandwich
Lets go back to our peanut butter sandwich algorithm
MakePeanutButterSandwichWith(condiment):
get bread out of pantry
take bread out of bag

get peanut butter out of pantry


spread peanut butter on bread
put peanut butter back in pantry

get condiment out of pantry


spread condiment on bread
put condiment back in pantry

put bread back in pantry


give person their sandwich
Improved sandwich

MakeSandwichWith(condiment1,condiment2):
get bread out of pantry
take bread out of bag

get condiment1 out of pantry


spread condiment1 on bread
put condiment1 back in pantry

get condiment2 out of pantry


spread condiment2 on bread
put condiment2 back in pantry

put bread back in pantry


give person their sandwich
Improved sandwich
MakeSandwichWith(condiment1,condiment2,condiment3):
get bread out of pantry
take bread out of bag

get condiment1 out of pantry


spread condiment1 on bread
put condiment1 back in pantry

get condiment2 out of pantry


spread condiment2 on bread
put condiment2 back in pantry

get condiment3 out of pantry


spread condiment3 on bread
put condiment3 back in pantry

put bread back in pantry


give person their sandwich
Lists
A list is a way we can store an arbitrarily large number of
values inside of one variable.
Note: The terms list and array can be used interchangeably.
Lets go create pseudo-code
Improved sandwich (pseudo-code)

MakeSandwichWith(condimentList):
get bread out of pantry
take bread out of bag

for condiment in condimentList:


get condiment out of pantry
spread condiment on bread
put condiment back in pantry

put bread back in pantry


give person their sandwich
MakeSandwichWith(condimentList):

Improved sandwich (pseudo-code) get bread out of pantry


take bread out of bag

for condiment in condimentList:


get condiment out of pantry
spread condiment on bread
put condiment back in pantry

put bread back in pantry


give person their sandwich

The Main
MakeSandwichWith( [peanut butter, marshmallow fluff, jelly, cheese] )
MakeSandwichWith( [jelly] )
MakeSandwichWith( [] )
Formally
Lists (Creating a list)
Three parts to lists: Creating a list, accessing
elements from the list, and modifying the list.
Creating a list:
We create a list by using the [ ] operator val = [20,40,20,3]
Each value in the list is separated by a comma. x = 55
bop = [33,x,-12]
Lists could be empty or contain a single element. noList = []
Its good practice to make elements in the list single = [55]
the same type
Not required in Python, but will save you pain.
Accessing Elements
Two main ways to access elements: all elements or single
element.
All elements:
The best way to access all elements is to use a for loop.
Which has the syntax

for element in theList:

element is a variable for the duration of the iteration


Example

myList = [20,30,-10,50]

print("Starting")
for val in myList:
print(myList)
print("ending")

thing = [-33,12,55]
for a in thing:
if a > 0:
print("I'm positive")
else:
print("Don't be negative")
Question
How would you sum up all values in a list?
How would you average all values in a list?
Single Value
You can access a single value at a time by using the [] as well
The syntax is as follows
myList[index]

where index indicates, in order, which element you want.


Index
Youre probably use to the first element in a list being element
1
In computer science, lists begin with 0
There are good reasons for this, that we wont talk about here.
myList = [20,30,-10,50]

Index 0 1 2 3

Value 20 30 -10 50
Example

myList = [20,30,-10,50]

x = myList[0]
print(myList[2])
print(x)
myList[1] = 500
print(myList[1])
Out of Range
What happens if you have a list of 4 elements and you try and
access the 5th element in the list (i.e., index 4).
myList = [20,30,-10,50]
x = myList[4]

It CRASHES!
This will look like it works, when you write your code
But it will give you an array out of bounds error when you
run your program.
Negative Value?
What happens if you tried to access the value at index -1?
It gives you the last value in the array.
Negative values go from back to front.

myList = [20,30,-10,50]
x = myList[-1]
Changing the list
Changing the value of an element is easy: just use the []
operator

hello = [20,30,40,50]
hello[0] = 55
Bad For Loop, BAD!
You cant change values using the for loop though.
When you try and change the element you change the
variable holding the value NOT the value in the list
hello = [20,30,40,50]
for element in hello:
element+=20

print(hello)
hello = [20,30,40,50]
for element in hello:

Changing with while Loops element+=20

print(hello)

You can use while loops and [] to do correctly what the


above code tries to do.
How?
Hint: you can get the size of a list by using: len(hello)
Adding Elements
We add elements to an array by using two different approaches
We can concatenate lists using the + operator
Order matters.
We can add individual elements by using the append operation.
Adds it to the end.

myList1 = [50, 60, 80]


myList2 = [100, 120, 130]
combined = myList1+myList2

data = [20,30,40]
data.append(50)
Remove Element
We can remove an individual element from the array by using
the remove command like so
data = [20,30,40,50,90]
data.remove(30)
Multidimensional Arrays
Spreadsheets
We can use arrays to make spreadsheets as well!
row/col 0 1 2
0 20 200 70
1 30 300 80
2 40 400 90
3 50 500 100
4 60 600 110
What is an array?
Its a list of lists.
Spreadsheets
We can use arrays to make spreadsheets as well!
row/col 0 1 2
0 20 200 70
1 30 300 80
2 40 400 90
3 50 500 100
4 60 600 110
What is an array?
Its a list of lists.
row/col 0 1 2

Making it 0
1
20
30
200
300
70
80
2 40 400 90
3 50 500 100
4 60 600 110

row0 = [20,200,70]
row1 = [30,300,80]
row2 = [40,400,90]
row3 = [50,500,100]
row4 = [60,600,110]
total = [row0,row1,row2,row3,row4]
print(total[3][1])
row/col 0 1 2

Making it (Shorthand) 0
1
20
30
200
300
70
80
2 40 400 90
3 50 500 100
4 60 600 110

total = [[20,200,70],
[30,300,80],
[40,400,90],
[50,500,100],
[60,600,110]]
print(total[3][1])

You dont need to write it over multiple lines, but its a lot
easier to read. Whats important is the double [[ and ]]
For Loop
You can use for loops to go through the multidimensional
total = [[20,200,70],
[30,300,80],
[40,400,90],
[50,500,100],
[60,600,110]]

for row in total:


for element in row:
print(element)

each row takes on the row in total (and its a list) so we need
to go through them one at a time.
Tuples
Data Structures and Tuples
A data structure is any construct designed to hold multiple
pieces of information.
Lists are the the most widely used type of data structures.
Tuples are another data structure that is similar to lists, but
they cannot change their size after they have been created.
Make a Tuple
We make a tuples using ()
point = (4,5)

We access elements of tuples the same way we do as for lists.


Tuples are useful when you have a set of data that is a specific
size.
For example, (x,y)-coordinates.
You never need to use a tuple. You should just use them when
appropriate.
Dictionary
Dictionary
Another type of data structure is a dictionary
A dictionary is similar to a list except that elements are
accessed by a key rather than an index.
An index is always an integer.
A key can be any type of variable.
Make a Dictionary
You make a dictionary using the {}
For every value, you need to define a key.
Each key-value pair is separated using a comma
We use a colon to designate a key:value
Keys can be any type, but are usually strings
dict = {Catie":28, Ally":25, Kim":32, Chad":30}
Accessing
Again, you can access elements from dictionaries individually
or using the for loop.
Use the [] to access a value
for loops give you the key. To get the value, you need to use
the [] operator

dict = {Catie":28, Ally":25, Kim":32, Chad":30}


print(dict[Catie"])

for key in dict:


print(key)
value = dict[key]
print(value)
Adding/Changing Elements
You add elements and change elements the same way.
You do this by assigning a key a specific value.

dict = {Catie":28, Ally":25, Kim":32, Chad":30}


dict[Catie"] = 100 #change
dict[Valerie"] = 19 #adds
Removing Element
You can remove elements from a dictionary by using the pop
command

dict = {Catie":28, Ally":25, Kim":32, Chad":30}


dict.pop(Catie")
Practice
You are given two lists, one containing students names and one containing
their quiz scores. Write a function, makeDictionary, that takes the two lists
and returns a dictionary with the names as the key and the scores as the values.
Use makeDictionary to create a dictionary dictionary with the following data:
names = ['Joe', 'Tom', 'Barb', 'Sue', 'Sally'], scores = [10,
23, 13, 18, 12]. Store the output in a variable called scoreDict.
Using scoreDict, find Barb's score.
John took the quiz late and got a 19. Add John and his score to scoreDict.
Sally's score was incorrectly recorded. Update her score to be 15.
Tom just dropped the class. Delete Tom and his score from scoreDict.
Write a function, dictAvg, that takes a dictionary as a parameter and returns
the average score for that dictionary. Test this function with scoreDict.

Вам также может понравиться