How To Add Items To A List In Python

In this tutorial, we will learn how to add items to a list in Python. Lists are mutable ordered sequences of elements, which means they can be changed after they are created, unlike strings and tuples.

The elements can be of any type, including numbers, strings, and other objects. This makes lists very versatile and an essential part of the Python programming language.

Step 1: Create a List

First, let’s create a list. To create a list, you can use square brackets [] and separate the elements with commas. Let’s create a shopping list:

Step 2: Use the append() Method

The easiest way to add items to a list is to use the append() method. This method adds an element to the end of the list. For example:

Now, our list should look like this:

['milk', 'eggs', 'bread', 'cheese']

Step 3: Use the insert() Method

Another way to add items to a list is to use the insert() method. This method takes two arguments: the index where you want to add the element and the element itself. Let’s add an item to the beginning of our shopping list:

Our list should now look like this:

['fruit', 'milk', 'eggs', 'bread', 'cheese']

Step 4: Use the extend() Method

If you want to add multiple elements to the list at once, you can use the extend() method. This method takes a list or an iterable as an argument and adds the elements to the end of the list. Let’s add ‘meat’ and ‘fish’ to our shopping list:

Our list should now look like this:

['fruit', 'milk', 'eggs', 'bread', 'cheese', 'meat', 'fish']

Step 5: Using the + Operator

Another way to add items to a list is to use the + operator to concatenate two lists. For example:

Our list should now look like this:

Full Example Code:

Output:

['fruit', 'milk', 'eggs', 'bread', 'cheese', 'meat', 'fish', 'vegetables', 'rice']

Conclusion

In this tutorial, we covered different ways to add items to a list in Python, such as using the append(), insert(), and extend() methods, as well as the + operator.

With these methods in your toolkit, you should be able to manipulate Python lists with ease. For more information on Python lists, you can refer to the official Python documentation.