Exploring Misconceptions About .append()
In this lesson, you’ll see two common misconceptions about the
.append() method in the hopes that you won’t try to use
.append() the wrong way. First is that
.append() only adds a single element to a list.
.append() still treated the tuple as a single item and added that as a fifth item to the list. This doesn’t recreate the effect that the slice operation in the last lesson demonstrated. To do that, you’ll need to use the
And you can extend your list with a tuple and it will again have the same desired effect: a new list with individual elements for what you are extending on to the original list. So, use
.append(), when you want to add multiple items to a list, which was the behavior you saw with the slice operation before.
Another thing to remember is that
.append() doesn’t return a list to use.
.append() does its work in place. That means it actually modifies the object you call it on. It doesn’t return a new or modified version of the list.
Technically, it returns
None, but that basically means you shouldn’t plan on using it as if it’s going to return something meaningful. So, look at this. You can create a list and while calling
.append() to it, save the return value to a variable.
But when you try to inspect that variable, you don’t see anything because it’s a reference to
None, which basically means it’s not a reference to anything meaningful in this context. If you want to see the modified list, that’s still in
x itself was modified.
The work was done in place. So again, don’t try to use any return value from a call to
.append(). Don’t even save it. The list you use it on is being modified by adding the new element to the end of that same list. We call that doing the work in place.
Become a Member to join the conversation.