Check out a free preview of the full Python Fundamentals course

The "Adding Items to a List" Lesson is part of the full, Python Fundamentals course featured in this preview video. Here's what you'd learn in this lesson:

Nina introduces the append, insert, and extend methods built into python.

Preview
Close

Transcript from the "Adding Items to a List" Lesson

[00:00:00]
>> Nina Zakharenko: If we want to add items to our list, there's a few ways of doing it. So let's start with a
>> Nina Zakharenko: New list of names, and it just has two items in it. In order to add something in at the end, we use the append method like we saw Earlier so we just call .append on names and we pass in the value that we wanna append to the list.

[00:00:31]
Now, if we look at names, there are three. And of course, len of names returns three. We can also use the insert method, to insert values into an arbitrary position. And the insert method takes two variables. The first is, let's say, it's my_list. The first is the position that you wanna insert at, and the second is the value.

[00:01:07]
>> Nina Zakharenko: So doing that, if I wanted to insert an item, a new name Rose, at the very start of my list, what I call here, what's the position?
>> Student: Zero.
>> Nina Zakharenko: Position is zero, why is that?
>> Student2: Zero-based list.
>> Nina Zakharenko: Zero-based indexing for the list, exactly right. And then, the second argument would be Rose, the name that I wanna insert.

[00:01:37]
So now if I look at my list of names, we'll see that Rose is right there in the beginning. And again, if we forget the order we can do a help on list.insert. And insert object before index, it will give us the arguments index first, object after. There is another way of adding to a list.

[00:02:07]
Let's say we had two lists.
>> [NOISE]
>> Nina Zakharenko: And should you add a new item to a list but what if you want to combine two list together? To do that, you would use the extend function.
>> Nina Zakharenko: Now if I take a look at my list of names, it's Nina, Max, followed by Red, Blue.

[00:02:42]
That second list was kind of extended exactly as it is because lists have an order.

Learn Straight from the Experts Who Shape the Modern Web

  • In-depth Courses
  • Industry Leading Experts
  • Learning Paths
  • Live Interactive Workshops
Get Unlimited Access Now