![]() |
Appending elements to a list is a common operation in Python, and it’s essential to understand how to add elements to an empty list. In this article, we’ll explore different methods to append items to an empty list and discuss their use cases. Append Element to an Empty List in PythonBelow are some examples by which we can append to an empty list in Python:
Append to an Empty List Using the append MethodThe append() method in Python is a built-in list method. Here, you can add the element to the end of the list. Whenever you add a new element, the length of the list increases by one. In this example, we are going to create an empty list named sample_list and add the data using the append() method. Python3
Output
[1, 'GeeksForGeeks', 4.14] Append to an Empty List Using extend methodThe extend() method in Python is a built-in list method. This method takes multiple elements as input in a single operation. Whenever you add a new element, the length of the list increases accordingly. In this example, we are going to create an empty list and name it sample_list_1, then add the data or values using the extend method. Python3
Output
[1, 2, 3, 'GeeksForGeeks', 3.14, True] Append to an Empty List Using Insert methodThe insert() method in Python is a built-in list method. Here you can add the single element in a specified index in a list. Whenever you add a new element, then the length of the list increases by one. The insert method requires two arguments to be passed. In this example, we are going to create an empty list named sample_list_2 and add the data or values using the insert method. Python3
Output
[1, 'GeeksForGeeks', 3.14, False] Append to an Empty List Using ‘+=’ operatorThe ‘+= ‘ is used for concatenating the list. Here you can add multiple elements at a time. The length of the list grows dynamically. In this example, we are going to create an empty list named sample_list_3 and add the data or values using the ‘ += ‘ operator. Python3
Output
[1, 'GeeksForGeeks', 3.14, True] |
Reffered: https://www.geeksforgeeks.org
Python |
Type: | Geek |
Category: | Coding |
Sub Category: | Tutorial |
Uploaded by: | Admin |
Views: | 13 |