In this tutorial, we will learn how to append each item in a list using Python. This is a fundamental concept in Python and is widely used in various applications. By the end of this tutorial, you will be able to append items in a list using different methods in Python.
Step 1: Create a list in Python
Firstly, let’s create a list in Python. A list is a mutable, ordered sequence of items. The syntax for creating a list is using square brackets. Add some elements, such as integers or strings, separated by commas.
1 |
my_list = [1, 2, 3, 4, 5] |
Step 2: Appending items to a list using the append() method
The most common way to append items to a list is by using the append() method. This method adds an item to the end of the list. The syntax for using the append() method is:
1 |
list_name.append(item) |
Let’s see an example:
1 2 3 4 5 |
my_list = [1, 2, 3, 4, 5] my_list.append(6) print(my_list) |
Output:
[1, 2, 3, 4, 5, 6]
Step 3: Appending items using the + operator
You can also use the + operator to append items to a list. This method is particularly useful when you have two lists and you want to concatenate them. Since the + operator is expecting another list, you can pass the item as another list like below:
1 2 3 4 5 |
my_list = [1, 2, 3, 4, 5] my_list = my_list + [6] print(my_list) |
Output:
[1, 2, 3, 4, 5, 6]
Full code:
1 2 3 4 5 6 7 8 9 |
my_list = [1, 2, 3, 4, 5] # Appending items using the append() method my_list.append(6) print("Using append():", my_list) # Appending items using the + operator my_list = my_list + [7] print("Using + operator:", my_list) |
Output:
Using append(): [1, 2, 3, 4, 5, 6] Using + operator: [1, 2, 3, 4, 5, 6, 7]
Conclusion
In this tutorial, we learned how to append each item in a list using Python.
The primary method is using the append() method, which adds the item to the end of the list. Alternatively, we can also use the + operator to concatenate lists.
Now, you can easily append items to your lists in your Python applications.