Adding Elements to a Python List

17-04-23 Ahmed Obaid 4522 0

Python provides a set of techniques and methods that can help you add elements to a list.

Method 1: Using the append() functio

One of those methods. .using the append() function. Items can be added to the list using the built-in append() function. Only one item at a time can be added to the list using the append() function, to add multiple items using the append() function, and by using loops.

Example:


# Create a list
List = [1, 2, 3]
# Add items
# in the list
List. append(4)
print (List)

The output will be:


[1, 2, 3, 4]

In the previous example, we added an item to the list using the append() function. The append() function adds a new item to the end or the right side of the list. The following diagram shows the process:

Note: You have to keep in mind that the append() function only adds one or more items at a time.

Note: You can add multiple elements using the append() function by using loops.

Method 2: Using the insert() function

The append() function only works to add items at the end of the list, and to add items at a specific position, the insert() function is used. Unlike the append() function which takes a single argumentundefined Only, the insert() function requires two arguments, position and value.

 Example:


 # Create a list
 List = [1, 2, 3, 4]
 # Add items
 # in the list
 #insert() Adds the element to a specified location using a function
 List.insert(2 , 6)
 print (List)

 The output will be:


 [1, 2, 6, 3, 4]

 Example:


 # Create a list
 List = ['Welcome', 'Python']
 # Add items
 # in the list
 #insert() Adds the element to a specified location using a function
 List.insert(1, 'to')
 print (List)

 The output will be:


 ['Welcome', 'to', 'Python']

 Method 3: Using the extend() function

Other than the append() and insert() functions, there is another way to add items to the list, and that is with the extend() function. This method is used to add multiple items at the same time at the end of the list.

 Example:

 


# Create a list
 List1 = [1, 2, 3, 4]
 List2 = [5, 6, 7, 8]
 # Add items
 # in the list
 #extend() Add multiple items to the end of the list on the right using a function
 List1. extend(List2)
 print (List1)



 The output will be:


 [1, 2, 3, 4, 5, 6, 7, 8]

 Note: The append() and extend() functions can only add elements at the end of an app the list.

 See a detailed explanation of the append() and extend() functions in Python

External sources:

 Lists - The official Python documentation

 If you have any questions or concerns, leave them in the comments



Tags


Python python data types Python List extend() Method Python List append() Method Python List insert() Method Adding Elements to a Python List

Share page