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.
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.
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.
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.