Adding Element in List in Python
Let’s look at some built-in list functions in Python to add element in a list.
1. Python append() Method
Adds element to the end of a list.
Syntax: list.append (element)
Example:
# Adds List Element as value of List.
List = ['Mathematics', 'chemistry', 1997, 2000]
List.append(20544)
print(List)
Output
['Mathematics', 'chemistry', 1997, 2000, 20544]
2. Python insert() Method
Inserts an element at the specified position.
Syntax:
list.insert(<position, element)
Note: The position mentioned should be within the range of List, as in this case between 0 and 4, else wise would throw IndexError.
Example:
List = ['Mathematics', 'chemistry', 1997, 2000]
# Insert at index 2 value 10087
List.insert(2, 10087)
print(List)
Output
['Mathematics', 'chemistry', 10087, 1997, 2000]
3. Python extend() Method
Adds items of an iterable(list, array, string , etc.) to the end of a list.
Syntax: List1.extend(List2)
Example:
List1 = [1, 2, 3]
List2 = [2, 3, 4, 5]
# Add List2 to List1
List1.extend(List2)
print(List1)
# Add List1 to List2 now
List2.extend(List1)
print(List2)
Output
[1, 2, 3, 2, 3, 4, 5] [2, 3, 4, 5, 1, 2, 3, 2, 3, 4, 5]
Python List methods
Python List Methods are the built-in methods in lists used to perform operations on Python lists/arrays.
Below, we’ve explained all the Python list methods you can use with Python lists, for example, append(), copy(), insert(), and more.