Python List append() Method

The append() method in Python is a built-in function used to add an element to the end of a list. The method modifies the list in place, meaning that it adds the element to the end of the list and does not return a new list. In this article, you will learn how to use the append() method with examples.

Syntax

list.append(element)

Parameters

  • element: The element to be added to the end of the list.

Examples

Example 1: Append an Element to an Empty List

Let’s consider an empty list and try to append an element to it using the append() method:

>>> a = []
>>> a.append(10)
>>> print(a)
[10]

In this example, we have created an empty list a and then used the append() method to add the number 10 to the end of the list. Finally, we have printed the list, which now contains a single element with the value 10.

Example 2: Append Multiple Elements to a List

You can use the append() method multiple times to add multiple elements to a list:

>>> a = [1, 2, 3]
>>> a.append(4)
>>> a.append(5)
>>> print(a)
[1, 2, 3, 4, 5]

In this example, we have created a list a with three elements and then used the append() method twice to add two more elements to the end of the list. Finally, we have printed the list, which now contains five elements.

Example 3: Append a List to a List

The append() method can also be used to add a list to the end of another list:

>>> a = [1, 2, 3]
>>> b = [4, 5, 6]
>>> a.append(b)
>>> print(a)
[1, 2, 3, [4, 5, 6]]

In this example, we have created two lists a and b. We have used the append() method to add the list b to the end of the list a. Finally, we have printed the list a, which now contains four elements including the list b as the last element.

Note that the above example results in a nested list, where the last element of the list is a list. To avoid this, you can use the extend() method instead of the append() method to add the elements of one list to another list. The extend() method adds the elements of the second list to the end of the first list, rather than adding the second list as a single element.

Conclusion

In conclusion, the append() method in Python is a simple and efficient way to add an element to the end of a list. Whether you want to add a single element or multiple elements to a list, the append() method provides a convenient way to do so. In this article, we have discussed the syntax, parameters, and examples of the append() method. You can now use this method with confidence in your own Python projects.

Leave a Reply

Your email address will not be published. Required fields are marked *