Append Element to an Empty List In Python
Last Updated :
12 Feb, 2024
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 Python
Below are some examples by which we can append to an empty list in Python:
- Using the append() method
- Using the extend() method
- Using the insert() method
- Using the ‘+=’ operator
Append to an Empty List Using the append Method
The 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
sample_list = []
sample_list.append( 1 )
sample_list.append( "GeeksForGeeks" )
sample_list.append( 4.14 )
print (sample_list)
|
Output
[1, 'GeeksForGeeks', 4.14]
Append to an Empty List Using extend method
The 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
sample_list_1 = []
additional_list = [ 1 , 2 , 3 , "GeeksForGeeks" , 3.14 , True ]
sample_list_1.extend(additional_list)
print (sample_list_1)
|
Output
[1, 2, 3, 'GeeksForGeeks', 3.14, True]
Append to an Empty List Using Insert method
The 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
sample_list_2 = []
sample_list_2.insert( 0 , 1 )
sample_list_2.insert( 1 , "GeeksForGeeks" )
sample_list_2.insert( 2 , 3.14 )
sample_list_2.insert( 3 , False )
print (sample_list_2)
|
Output
[1, 'GeeksForGeeks', 3.14, False]
Append to an Empty List Using ‘+=’ operator
The ‘+= ‘ 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
sample_list_3 = []
new_list = [ 1 , "GeeksForGeeks" , 3.14 , True ]
sample_list_3 + = new_list
print (sample_list_3)
|
Output
[1, 'GeeksForGeeks', 3.14, True]
Share your thoughts in the comments
Please Login to comment...