Tip:
Highlight text to annotate it
X
Unit 1 introduces a lot of new list methods that you may never have seen.
Let's talk about count, sort, and reverse.
List.count(x) returns the number of occurrences of x in the list.
Here we've just called it list.
The way you would use this is you would write the name of your list here
and whatever element you want to count.
I should mention that I've basically taken this description straight from the Python documentation.
List.sort sorts the list in place, and I'll talk a little bit more about what "in place" means later.
List.reverse does what you would think.
It just reverses the elements of the list, and again it does so in place.
Now, let's try using these methods.
Let's define a list of the Udacity professors.
In this list I've included all of the professors of the six classes,
and you'll see that Dave's name comes up twice.
This is because Dave teaches two of the classes.
Also, it makes this problem a bit more interesting.
Let's say we want to know how many times Steve's name shows up on this list.
For this example, it's pretty easy to count ourselves, but let's have Python do it anyway.
We'll define a variable called "stevecount" and set it equal to this.
Here the name of our list.count, and I'm counting the occurrences of Steve.
If I print stevecount, I get 1--just as I'd expect.
We could also count the number of occurrences of Dave.
When I run this I get 2, as expected--Dave and Dave.
Okay, now let's see what happens when we sort this list.
We'll define a new variable called "sortedprofs" and set it equal to udacityprofs.sort.
When I print sorted profs, I get None. Wait. What happened here?
I would have expected a sorted version of this list,
and this is where that "in place" comes from that I was talking about before.
Methods that work in place only modify the existing list.
They modify udacityprofs. They do not create a new list.
In fact, since we've just sorted udacityprofs let's see what happens when we print udacityprofs.
Now you can see that they've been sorted in alphabetical order.
Isn't mutability just wonderful?
Now, poor Wes is alway at the end of these sorted lists.
Let's give Wes some love by reversing this list.
Just as we'd expect, this is the same list but sorted in reverse alphabetical order.
There is plenty other Python list methods.
Feel free to check out the link below this video to see them.