Python: Adding items to a List

Python: Adding items to a List

Understanding how we can add items to a List in python

Today we will learn how we can add items to a list in Python.

Let's imagine you have a list in python, a list of all the groceries you want to buy for your week.

groceries = ['Milk', 'Bread', 'Oranges', 'Apples', 'Biscuit']

Now imagine you want to add one more item 'Shampoo' to your list, how will you do that?

Well obviously you can go and add that to the above list manually, but that's lame, isn't it? We will do it the fancy way using python.

1. Append (append)

To add an item to a list in python there is a method we can use append.

groceries = ['Milk', 'Bread', 'Oranges', 'Apples', 'Biscuit']

groceries.append('Shampoo')

print(groceries)
# Output: ['Milk', 'Bread', 'Oranges', 'Apples', 'Biscuit', 'Shampoo']

What we are doing in the above code?

  1. We are calling the append method on the list groceries
  2. Since the append method takes in an item that you want to append as a parameter we are passing Shampoo as a parameter.

2. Extend (extend)

Now imagine you want to add multiple items to the list of groceries, let's say Shampoo and Soap, how can we do that? well, we have a method extend which we can use.

groceries = ['Milk', 'Bread', 'Oranges', 'Apples', 'Biscuit']

groceries.extend(['Shampoo', 'Soap'])

print(groceries)
# Output: ['Milk', 'Bread', 'Oranges', 'Apples', 'Biscuit', 'Shampoo', 'Soap']

What we are doing in the above code?

  1. We are calling the extend method on the list groceries
  2. Now extend method takes in a list of items as a parameter so we are passing the list of items we want to append in this case ['Shampoo', 'Soap'].

3. With the + operator

There is also a different way to add items to a list by using the + operator

groceries = ['Milk', 'Bread', 'Oranges', 'Apples', 'Biscuit']

groceries = groceries + ['Shampoo', 'Soap']

print(groceries)
# Output: ['Milk', 'Bread', 'Oranges', 'Apples', 'Biscuit', 'Shampoo', 'Soap']

What we are doing in the above code?

  1. We are using the + operator to add a list of items ['Shampoo' + 'Soap'] to the existing groceries list.

Well, this was a quick look at how we can add an item to a list in Python, but what if we want to add an item or items in between or at the start of a list? Let's check that out in our next article! :)

Hope you like this post!