Hello and welcome to Chapter Ten of Python for Informatics, the chapter on tuples.
I'm Charles Severance. I'm your lecturer and I'm the author of the textbook.
As always, this material is copyright Creative Commons Attribution,
including the video lectures, the slides, and the book.
So tuples are the third kind of collection that we've talked about.
We've talked about lists and
we've talked about dictionaries.
And in the dictionary lecture, we kind of alluded to tuples.
We don't have to talk too much about tuples, it's really
shortening the lecture by telling you that they're a lot like lists.
They're a, non-change, they're a non-changeable list.
And, and the syntax of them is
pretty much the same as a list except
that we use parentheses instead of square brackets.
Okay? And so
like here is a three-tuple, a tuple
with three items in it, Glenn, Sally, and Joseph.
They are numbered zero, zero, one, and two.
So the second thing is one. So x sub two is indeed Joseph.
You know, we can pass them in as sequences to things like max or min or sum.
And so the maximum of 1, 9, 2 is 9.
And we can loop through them.
So here is y, it's a tuple.
It's 1, 9, 2. And iteration is going to through the three, three values, right?
And so it's going to print out 1, 9, 2, which runs the intended code once for
each of the values inside the tuple.
And so in this respect they're very much like lists.
But they're also different than lists in some real valuable ways.
Tuples are immutable, and so if you recall
when we talked about lists, we compared them to strings, because
both lists and strings are a sequence of elements where
the first one is zero, one, two, and et cetera.
But if we, if we look at a string for
example, and we have a three-character string A, B, C.
And we want to change the third character, y sub two, to D,
it complains and says, no, you can't do that.
But you can do it on a list, so if we have a list 9, 8, 7, and we
say x sub two is 6, which is the third
item, then the third item changes from 7 to 6.
Okay?
So this is mutable. This is not mutable.
And tuples are also like not, are not mutable.
They're like strings, they're sort of like lists, in terms of what they can store.
But they're like strings in the fact that they can't be changed.
So here we create a three-tuple, a three-item tuple, and we try to change
the third thing from 3 to 0 and it says you can't do that, not mutable.
Okay?
So, so it's kind of like lists in the kind of data that we store them, we
store in them, and it's kind of like strings in that
you can't change them once you create them.
So this parentheses, this constant, is the moment of creation. Once
you've put the things in, you can't fiddle around with them.
There's a bunch of other things you can't do with tuples.
You think why am I even, why even use tuples?
We'll get to that in a second.
So here is a three-tuple
with the numbers 3, 2, 1.
You can't sort it, because if you sorted it, that would change it.
You can't add to it.
You can't append the value 5 to the end of it, because that would change it.
And you can't reverse it. So, none of these are allowed.
Those are things you can do with lists, but you can't do with tuples.
And you can read the documentation, but we
can also use that built-in dir function, that really
awesome dir function, where we make a list and we say hey, Python,
what will you let me do with lists?
Well, you can append, count, extend, index,
insert, sort, reverse, remove, pop. Lots of things.
Now we make a tuple and say hey, Python, what can we do with tuple?
Well, you can do a count or an index,
which means you can't do all these other things.
So this is sort of a, a very much a reduction.
because everything you can do with tuples, you can do with lists.
But not everything you can do with lists, you can do with tuples.
So why?
Why did I just waste all this time introducing tuples?
All they are is have parentheses.
What good are they?
Well, it turns out that they're much more efficient.
Because Python doesn't have to deal with
the fact that we, as programmers, might change them,
Python can make them quicker, they can use less memory,
all kinds of things that save a lot of processing time in Python.
So when would you use a tuple?
Well, in particular, if you're going to
create some list that you're never changing, we prefer to use tuples.
And there's a lot of situations in
programming where we create what we think of as a temporary variable.
And if we're going to use, create it, use it, and throw it
away without ever modifying it, we prefer tuples in those kinds of situations.
Okay? So we prefer tuples when we create things that are just temporary.
It's the fact that they're temporary variables.
They're like temporary lists. Because they're efficient.
They're quick to make and they're quick to
get rid of, and they're quick to go through.
Now, another really neat thing about Python that I
really like is that is the fact that you can
do sort of two assignments in one by putting a tuple on
both the left and the right-hand side of your assignment statement.
So if we think about an assignment statement,
I like to think of it as having a direction.
It says, these things go there.
Well, in Python, you can actually send two things at the same time.
The 4 goes into the x and the fred goes into the y.
This is a tuple. This is a tuple.
You, you cannot have constants on this left-hand side.
You can have variables or constants on the, or expressions
on the right-hand side, but this must be two variables.
Similarly, in this, the 99 goes into a and the 98 goes into b.
Now, it turns out that you can
syntactically eliminate the parentheses if you really want.
And so this leads to a prettier syntax,
I think.
It's the exact same thing with or without parentheses, where we basically just say,
hey, come back, a and b are assigned to the tuple 99, 98.
And so you can eliminate the parentheses as long
as it's very clear what's going on in the tuple.
And so this, this might be a little disquieting
when you first see it, but it's just a
tuple with no parentheses and the 99 goes to the a and the 98 goes to the b.
Now, it turns out we already did this.
I sort of blew by this in the previous lecture in dictionaries
because it allows us to go through the
dictionary's keys and values with two iteration variables.
And so, if you remember, here is a dictionary.
We put two items into it and and we can call d.items and get a list
of tuples, a list of two-tuples.
Two-tuples are a quick way of saying a tuple with two things in it.
It's a two-element list that consists each element is a two-tuple.
And it's the key and the value,
key and the value. And so if we just print this out, it's a list.
So then when we put this on a for loop, it
is a list, but the things inside the list are each a tuple.
Each thing inside the list is a tuple.
So, when this iteration variable goes to there,
it is like
this tuple is being assigned into k,v. Which means the key,
key goes into k and the value goes into v.
The name I picked for k and v don't matter, do not matter.
It's just, it's just the first the first one and the second one.
So k go, k and v point here. Then the next time through the loop, k
and v point here. And so that's
how csev 2 and Chen Wen 4 happen.
And so this is really a tuple assignment or a tuple iterating
through a list of tuple iteration variable or a pair of iteration variables
walking through the list, okay?
We don't do this a lot, and it's really quite, it's most heavily
used for this situation where you're going through a dictionary and you want to see
both the keys and the values.
And then you use this method inside of dictionary called d.items.
Another thing that's cool about tuples
are that they're comparable. So less than, greater than, equals.
And so, they look, they first compare the first, leftmost, thing, then
if that matches, they go to the second one, and then if that one matches,
they go to the third one.
And so if we're asking, is (0, 1, 2) less than (5, 1, 2).
And the answer is True.
And it only looks at the 0 and the 5, and that's less than, so away we go.
If we ask is (0, 1, 2000000) less than (0, 3, 4)?
Well, 0 and 0 match, so it goes to the second one.
1 and 3, well they don't match and they're less than,
so 1 is less than 3, so it
so it's True and it doesn't even look at these numbers because it doesn't have to.
Right?
In this one, it doesn't look at those numbers.
And now if we say, come here, is Jones, Sally less than Jones, Fred?
Well, it compares this and they're equal.
So then it has to look to the second one: is Sally less than Fred?
Well, no, because S is not less than F.
And so that answer is False. Is Jones, Sally
greater than Adams, Sam? Well Jones is greater than Adams, so it
never looks at these variables, and that turns out to be True.
So these are comparable.
Which means we can use the less than, less than or equal to,
greater than or equal to, equal to, or not equal to.
So we can use these operators on whole tuples.
Now this turns out to be quite nice,
because things that can be compared can also be sorted.
Okay?
So here is
[COUGH] a, b, and c. a maps to 10.
b maps to 1. c maps to 22.
If I look at d.items,
I get back a list of two-tuples, three two-tuples.
They are not sorted because dictionaries
aren't sorted. a maps to 10,
c maps to 22,and b maps to 1.
The order that these come out in is not something that we can control.
But if we put these items into a variable,
call it t, t is the list of tuples basically,
and then we tell it to sort, it can do comparisons between all these.
And it can sort them and now they're sorted
in key order: a, b, c.
Now you'll never get any keys that match
so it never looks at the second one, right?
Because there's one and only one key a or b or c.
The value 10 never gets looked at. So this ends up sort by keys.
Sort by keys. Okay, so this is the way to sort by keys.
We take a dictionary.
We get back a list of tuples, key-value tuples, then we sort that dictionary.
I mean, sort that list of key-value tuples. And then, it's sorted by key.
Okay? So that's one sort.
There is a built-in function in Python
called sorted, which takes as a parameter a list,
and gives you back a sorted version of that list.
So we can collapse these operations by saying, oh,
well d sub items is this list of tuples non-sorted.
But sorted of d sub items is that same list of tuples, but then sorted.
So immediately in one step we have
a, b, and c properly sorted.
And we can combine into all this into one nice little for
statement, where we say for k, v in sorted of d sub items.
So this is now going to first sort the key-value pairs by key.
And then k, v is going to run through them, so k's
going to be a, 10. Then it's going to, k's going to be b,
v is going to be 1. k is going to be c,
v is going to be 22.
So now we've printed these things out in alphabetical key order.
Okay?
So by adding sorted to d.items, that means that
this loop is going to run in key-sorted order.
Key-sorted order.
And that's because sorted takes a list and then returns, as a,
takes a list as unsorted list as input and returns a sorted list.
Okay?
Now, if we are doing something like our common problem of what's the most common word,
what if we want to say, what's the five most common words?
In that case, we probably want to sort in
descending order by the values, not the key.
Okay?
So we want sort by the values instead of the key.
So this is a situation where we're going to create a temporary variable.
So here's how we're going to do it.
Here is our dictionary with a, 10 and we want to sort now by
the values, we want to, you know, maybe see the most common or sort by the values.
And so we are going to make a temporary list
and then we are going to loop through the items.
So, so this is going to just loop through them and it's
going to loop through them in non-sorted order and we are
going to add using the append operation to this little list that we are making.
But we're going to add a tuple that is value, comma, key.
So if we make the value first and the key second in this tuple.
So this syntax here, this parentheses v comma k.
that means make a two-tuple with values from the v and
k variable.
And, append a list. So you're going to end up with a list of two-tuples.
So if we, if we take a look when we're all done with this, each of these is a tuple.
10, a gets appended; 22, c gets appended, and it was simply the opposite order.
The, the tuple, each of the tuples now has the value first and the key second.
Value first, key second.
So this is a bit of temporary data that
we've created, this is a bit of temporary data that we've created.
Then what we do is we call the sort method.
Sort, take this list. Lists are mutable. The individual tuples can't be changed, but
the order of the tuples can be changed because they are in a list.
tmp.sort, and then we're going to say reverse equals True
so you sort from the highest down to the lowest. Okay?
And now, tmp has been sorted
and now it is in a new order.
22, 10, 1 is what caused it to be sorted.
So we know that the biggest value is 22, the key
of c. Next biggest is 10 with a key of a.
And the smallest is a key of 1, a value of 1 with a key of b.
So the trick here is
if we want to sort in some other way, we just construct
a list where we put it in the order that we want it sorted.
And this is more important now.
The value is more important than the key. Now if we had another,
like a 22, f, it would sort first on the 22.
And then it would, it would sort the f, 1 after the c, 1.
Right?
So we don't have any duplicates.
But we could have the we could have the key of
c to 22 and we could have f also be 22.
Okay, so, take some time on this, get this one right.
So now I want to show you a program
that is going to show you the ten most common words.
We did a, a loop before
where we did the
most common word by doing a maximum loop at the end by looking
through all of the counts in a dictionary and then picking the maximum.
But what if you wanted the top ten?
Right, but that, that you don't want to write
a loop for that, so we're going to use sorting.
So here's what we're going to do. We're going to open a file.
We're going to create a empty counts dictionary.
Then we're going to
write a for loop that reads each line for line in fhand.
Then I'm going to split each line into
words, based on the spaces, using the dot split.
Then I'm going to loop through each word in each line
and use our histogram or dictionary pattern where
I say counts sub word equals counts dot get
word comma zero. That basically says
go look in counts.
If the word key exists, give me back
the value that's in that, otherwise give me zero.
So this both
creates the new entries and updates old entries.
All in one nice simple statement.
So at the end of this bit of code right here
we are going to have counts with keyword word-count pairs.
Okay? So, this is something we've done before.
It's just dictionaries, reading, splitting.
And then this pattern of how to accumulate in a dictionary.
Then what we're going to do is we are going to make a new list
called l-s-t and now we're doing this key-value in the items.
So this is going to go through the key-value pairs in this list, which is the
key-value pairs from the dictionary. Right?
But then we are going to create this temporary list
of tuples that are val, comma, key.
So val is like 20, the; 14, hello;
and that's what the list is going to look like, right?
It's going to be tuples,
but it's going to be the value and then the
key, rather than the key and the value.
This one here is key, value; this one here, l-s-t, is value, key.
Now that we have a list that's value, comma, key,
we are just going to sort it because now it's going to sort based on the first
thing in that tuple and we're going to reverse it
so the biggest values are near the top.
And so when we're all done this is going to be
a list, except it's going to be sorted based on the value.
So that's just one step to sort it.
So this is a good example of how we sort of go through some work, we get a data
structure, a list, the way we want it and
now we can sort of leverage the built-in sort.
We had to prepare a list so we could use the built-in sort.
We could do this by hand, but it'd be very difficult.
But it's easier to say I think
I'll make a list, and then I'll sort it.
Okay?
So I, you know, I made two lists basically.
I made the original one, then I made this one just for the purpose of sorting.
And now what I am going to do to print out the top ten
is I am going to write a for loop val, key.
Remember, this list l-s-t is value-key.
And I'm going to say for val, key in lst, using list slicing,
starting at zero, up to but not including
ten, which is indeed is the first ten items.
Now I'm going to print out key, value, so it's going to print out the, 22;
fred, 16; and so I'm going to first print the first ten.
So, this list is in val-key order, the tuples are val-key order.
And so I'm going to print it out in key-val just so that I print out in a way
that makes the most sense.
And so, this is a simple way to do a
simple histogram of the occurrence of words in a file.
So again, you should know this, you should know every line.
You should know every line.
Go back, review a couple times, but you should know,
you should know the meaning of every line of this.
And if you do, that's really good. So
as you become more powerful and capable inside Python, you will
realize that there are sometimes even shorter ways of doing things.
Now, what I'm showing you here is not that different than what was
on the previous page, it's just really dense, but you have to concentrate.
So if, I want you to understand what's on that previous page.
If you don't understand this, don't feel bad.
I am going to explain it to you but don't feel bad if you don't get it.
Okay?
So I'm just going to explain it.
If it doesn't feel right to you, go back and look at the previous page.
Okay.
So here we go. I am going to have a dictionary.
And then I'm going to print, in one line, sorted by value.
So we'll start from the inside out.
So this is a thing called list comprehension.
It looks like a list constant because we start with square brackets.
But this is a Python syntax that says construct dynamically
a list of tuples v, comma, k and I would like
you to loop through the items with k and v taking on the successive values.
So this is creating that reversed list where value and key
are the order of the items in each tuple.
And it's going to do that, so this is going to expand.
It's sort of like, it goes [SOUND] expands this,
it makes a temporary list, right now.
Now if you look on the previous slide we call that thing l-s-t.
But here we don't even call it l-s-t, and then once we have the list of tuples
in value-key order, then we simply take and pass that into sorted.
This is a function call,
the sorted function. And then, now I'm not reversing it, but the print statement prints
out its ascending order of the value 1, 10, 22.
Okay? So this you can, you can make these more
dense once you're a little more comfortable with what's going on.
It's sometimes easier to construct something that seems to have
steps, where you can put, you know, you can put
a debug print here,
you can put a debug print here, you can do a debug print here,
and you kind of see what's going on, right?
Whereas once you really understand this
you can, you can write some more dense Python.
When you understand this, it's okay.
Right?
So I'm not saying you're supposed to understand this, but I just want
to point out that it's possible to do this in a tighter fashion.
So,
tuples are like lists except that you can't change them.
Right?
You can't change lists. And now you can compare them, you can sort them.
You can sort lists of tuples. You can't sort within the tuple itself.
The two values on the left-hand side of the assignment statement, we can
use sorted, and we played with sorting dictionaries by key and value.
So,
that's kind of the end of this lecture.
And and so at this point I just want to kind of congratulate
you on making it through the first ten chapters of the book.
So I'll, I'll drink a cup of tea to you.
Here's your cup of tea, here's my toast to you.
in my Slitherin cup.
And so it's time for a graduation ceremony.
So, I'll give a
a little graduation speech here with my graduation hat on and this is my
this is my Slitherin wand and so, so the reason I am congratulating you at
the end of this chapter is that at this point, you kind of
know almost, you know all the fundamentals of programming.
Programming really comes down to what's called algorithms and data structures.
Sometimes we solve a problem by a clever series of steps that we put together.
And sometimes we solve a problem by creating a clever data structure.
And so the first few chapters were about algorithms. Steps,
loops, functions, very procedural. How you sort of create these threads of
stepping and do things a bunch of times or skip around or whatever.
And in the last three chapters that we've covered
we're talking about data structures. And programming
power comes when you combine algorithms and data structures.
Now in the next chapters, starting with Chapter Eleven, regular expressions,
we're going to learn sort of more clever ways of doing the same thing.
So you kind of know how to do a lot of stuff now.
From this point forward, you'll see, oh, boy, that's more clever.
Or we'll use a database. Oh, that's more clever.
But it's not fundamentally different. And so that's why it's important for you
to understand, before you leave this moment, to understand everything
that we've covered so far.
Loops, functions, strings, files,
tuples, lists, dictionaries, because they are kind of the foundation and everything
else will just kind of be a subtle refinement/improvement.
So once you understand that you've kind of begun, you've
become a basic programmer and I like, I like poof!
Like I, I like
magically asperio you and turn you into Pythonio, something like that.
Okay.
Enough with the Harry Potter reference.
Thank you for spending all this time with me.
If you've gotten this far, I really appreciate it.
And of course it's really just the beginning but
I hope that it has been a good beginning.
Thank you.