There are several ways to update the List in Python, let’s see them.
Different ways to update Python List:
Python list provides the following methods to modify the data.
- list.append(value) # Append a value
- list.extend(iterable) # Append a series of values
- list.insert(index, value) # At index, insert value
- list.remove(value) # Remove first instance of value
- list.clear() # Remove all elements
list.append(value):
If you like to add a single element to the python list then list.append(value)
is the best fit for you. The list.append(value) always adds the value to the end of existing list.
a_list = [1, 2, 3, 4]
a_list.append(5)
print(a_list)
Output:
[1, 2, 3, 4, 5]
list.extend(iterable):
The append and extend methods have a similar purpose: to add data to the end of a list. The difference is that the append method adds a single element to the end of the list, whereas the extend method appends a series of elements from a collection or iterable.
a_list = [1, 2, 3, 4]
a_list.extend([5, 6, 7])
print(a_list)
Output:
[1, 2, 3, 4, 5, 6, 7]
list.insert(index, value):
The insert()
method similar to the append() method, however insert method inserts the value at the given index position, where as append() always add the element at the end of the list.
a_list = [10, 20, 40]
a_list.insert(2, 30 ) # At index 2, insert 30.
print(a_list)
Output:
[10, 20, 30, 40]
If the provided index out of range, then the insert() method adds the new value at the end of the list, and it inserts the new value to the beginning of the list if the given index is too low.
a_list = [10, 20, 30]
a_list.insert(100, 40)
print(a_list)
a_list.insert(-50, 1)
print(a_list)
Output:
[10, 20, 30, 40]
[1, 10, 20, 30, 40]
list.remove(value):
The remove(value)
method removes the first occurrence of the given value from the list. There must be one occurrence of the provided value, otherwise the Python raises ValueError.
a_list = [1, 2, 3, 4, 5, 4]
a_list.remove(4)
print(a_list)
Output:
[1, 2, 3, 5, 4]
Removing min and max values from the list.
a_list = [1, 2, 3, 4, 5, 4, 7, 9 , -1]
a_list.remove(max(a_list)) # removed the max element from the list
a_list.remove(min(a_list)) # removed the min element from the list
print(a_list)
Output:
[1, 2, 3, 4, 5, 4, 7]
list.clear():
The clear()
method used to remove all the elements from the list. The same we can also do with del list[:]
a_list = [10, 20, 30, 40]
a_list.clear()
print(a_list)
Output:
[]
References:
Happy Learning 🙂