Think of Lists as Lists
00:00 Okay, nice work. You’re done with tuples for now. And in the next part of the course, you’re going to be focusing on lists. See what I did there? Tuples are out of focus.
00:10 All right, so let’s start off by what lists really are. A list is an ordered mutable sequence of values. Sounds similar to tuples but not quite. We’ll dive into this in just a moment. For a list, each element is again separated by a comma, and all elements are surrounded by a pair of square brackets.
00:29
So putting this together, a list literal would look like this, for example. So you have the three numbers again, [1, 2, 3]
. And they’re separated by commas from each other and surrounded by square brackets.
00:41 That’s a list in Python.
00:44 And a list is another sequence type in Python, just like strings and tuples are. And lists are similar to tuples in that both of them can contain items of any data type.
00:55
They’re both indexed by integers starting at zero. They both support slice notation. They both support the keyword in
to check for the existence of elements, and both of them are also iterable.
01:08 So in that sense, lists are similar to tuples,
01:12
but they are different to tuples because lists are mutable. This means that you can change elements in the list after you’ve created it. So here’s a small example again, with the numbers
collection here.
01:25
In this case, we’re making a numbers
list that consists of three elements again. So we have the square brackets, and then 1, 2, 3
in there.
01:32
And you see that in the second line, you are writing numbers[0]
and close the square bracket. So here you’re using indexing to access the first element in the list, and you’re reassigning it to a different value.
01:46
In this case, you’re reassigning it to the string "One"
. And then if you print out numbers
, you see that the first element in the list was changed from the integer 1
to the string "One"
.
01:58 So it could be anything, but this is just an example to show that lists are actually mutable. So when you did this earlier with the tuple, what you got was an error because tuples are immutable.
02:08 You can’t change elements in there, but lists are mutable. So you do that, and that’s a big difference that you’ll see has a lot of effects that ripple out throughout your use case between tuples and lists.
02:22 And you’ll learn more about that as the course goes on.
02:26 But let’s start off by talking about how you can create a list.
Become a Member to join the conversation.