How to Add Number to List in Python
To add a number to a list in Python, you can use the append() function, the + operator, or the insert() function.
The following examples show how to add a number to a list in Python using different methods.
Using append() Function
We can use the append() function to add a number to a list.
Suppose we have the following list:
# Declare list
list1 = [25, 27, 45, 36, 30, 25]
# Add number to list
list1.append(26)
# Show updated list
print("Updated list:", list1)
Output: 👇️
Updated list: [25, 27, 45, 36, 30, 25, 26]
In this example, we use the append() function to add the number 26 to the list list1.
Using + Operator
We can use the + operator to add a number to a list.
Suppose we have the same list as above.
We can use the following code to add the number 26 to the list:
# Add number to list
new_list = list1 + [26]
# Show updated list
print("Updated list:", new_list)
Output: 👇️
Updated list: [25, 27, 45, 36, 30, 25, 26]
In this example, we use the + operator to add the number 26 to the list list1 and store the result in new_list.
Using insert() Function
We can use the insert() function to add a number to a list at a specific position.
Suppose we have the same list as above.
We can use the following code to add the number 26 to the list at the first position:
# Add number to list
list1.insert(1, 26)
# Show updated list
print("Updated list:", list1)
Output: 👇️
Updated list: [25, 26, 27, 45, 36, 30, 25]
In this example, we use the insert() function to add the number 26 to the list list1 at the first position.