Hint: You can adjust the default video playback speed in your account settings.
Hint: You can set the default subtitles language in your account settings.
Sorry! Looks like there’s an issue with video playback 🙁 This might be due to a temporary outage or because of a configuration issue with your browser. Please see our video player troubleshooting guide to resolve the issue.

Understanding the Basics of .append()

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

00:22 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.

00:38 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.

01:29 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.

02:03 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 4.

02:27 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.

03:01 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.

03:23 So this list was extended by three elements to make room for 4, 5, and 6. That’s using slicing. The .append() method doesn’t function this way.

03:40 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.

04:12 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 .append().

Become a Member to join the conversation.