In this tutorial, we will be learning one of the basic yet very important concepts – How to append a list in Python.
Python lists are a versatile data type that allows us to store different types of data which might be integers, strings, and even lists. The append() function is a commonly-used function to add (or append) an element at the end of the list.
Step 1: Understanding the Basics
In Python, a list is considered a compound data type, which means you can have a list with a mix of different kinds of information, like integers and strings or even other lists. The syntax to create a list is simply to bracket comma-separated values:
1 |
List_name = [element1, element2, element3...] |
Step 2: Using append() Function
The append() function in Python adds a single item to the existing list. It doesn’t return a new list; rather it modifies the original list. The syntax of the append function is :
1 |
List_name.append(element) |
Step 3: Appending a list to another
Applying the append() function on a list adds the entire list as a single element at the end of the original list. Here is how you can do it :
1 2 3 |
list1 = [1, 2, 3] list2 = ['a', 'b', 'c'] list1.append(list2) |
This code will output:
[1, 2, 3, ['a', 'b', 'c']]
As you can see, the second list has been added as a single element at the end of the first list.
Full Code
1 2 3 4 |
list1 = [1, 2, 3] list2 = ['a', 'b', 'c'] list1.append(list2) print(list1) |
Conclusion
To summarise, the append() function in Python is a practical way to add elements to a list. It allows us to easily append values or even other lists. This can be particularly handy when you need to add items to your list based on some sort of computation or condition. Here is a detailed guide on Python’s data structures, including lists and their functions.