Understanding the Basics of .append()
In this lesson, you’ll see the basics of using the
.append() method. The
.append() method takes an object as an argument and adds it to the end of an existing list. For example, suppose you create a list and you want to add another number to it.
You would do so by using the
.append() method, by first typing the name of the list, followed by a dot, then the call to
.append(), putting in parentheses the object you wanted to add.
And now you can see that
4 has been added to the end of the list. In Python, the elements of a list can be any type of object, and
.append() can be used to add any type of object to the end of the list.
00:57 You can start with a list of integers,
01:06 add another integer, then maybe a string,
01:20 and then a decimal number.
So any type of object you have to add to the end of the list, you can use
.append() to do that. One way to interpret what
.append() does can be through the use of slicing.
01:45 You can start with a list and then use a slice operation to extend it.
So this notation will have the same effect as
.append(). So, what’s happening here? You’re taking a slice from
numbers—in this case, from
3 to the end—and then assigning that slice to an iterable—in this case, a list containing a single element
Since there is nothing at index
3 yet, Python unpacks this iterable and places the individual items at the end of the list. However, you shouldn’t take this interpretation too literally because
.append() only adds a single item to the end of a list but using the slice operation will lead to a different type of results.
So again, I’m going to take a slice from positions
3 to the end and set that slice equal to a longer iterable. Since
numbers doesn’t have any elements there, Python will add them to the next positions in order in this list.
So this list was extended by three elements to make room for
6. That’s using slicing. The
.append() method doesn’t function this way.
If I try to append… It helps if I type it right!
numbers.append(). If I try to append a list to the end of the existing list, we get a list of size
4 with the fourth element being that list, the first three elements still being those integers.
So again, don’t take this slice interpretation too literally. It only makes sense if you’re adding an iterable with a single element to the end of the list. In the next lesson, you’ll try to clear up some other misconceptions some programmers have when using
Become a Member to join the conversation.