Adding Elements to list¶
We can perform below operations to add elements to the list in Python.
append
- to add elements at the end of the list.insert
- to insert an element at the index specified. All the elements from that index will be moved to right side.extend
- to extend the list by appending elements from other list.We can also append the list using
+
l = [1, 2, 3, 4]
l.append?
Docstring: L.append(object) -> None -- append object to end
Type: builtin_function_or_method
l.append(5)
l
[1, 2, 3, 4, 5]
l = l + [6]
l
[1, 2, 3, 4, 5, 6]
l = l + [7, 8, 9, 10]
l
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
l.insert?
Docstring: L.insert(index, object) -- insert object before index
Type: builtin_function_or_method
l.insert(3, 13)
l
[1, 2, 3, 13, 4, 5, 6, 7, 8, 9, 10]
l.extend?
Docstring: L.extend(iterable) -> None -- extend list by appending elements from the iterable
Type: builtin_function_or_method
l.extend([11, 12])
l
[1, 2, 3, 13, 4, 5, 6, 7, 8, 9, 10, 11, 12]