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
+
In [1]:
l = [1, 2, 3, 4]
In [2]:
l.append?
Signature: l.append(object, /) Docstring: Append object to the end of the list. Type: builtin_function_or_method
In [3]:
l.append(5)
In [4]:
l
Out[4]:
[1, 2, 3, 4, 5]
In [5]:
l = l + [6]
In [6]:
l
Out[6]:
[1, 2, 3, 4, 5, 6]
In [7]:
l = l + [7, 8, 9, 10]
In [8]:
l
Out[8]:
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
In [9]:
l.insert?
Signature: l.insert(index, object, /) Docstring: Insert object before index. Type: builtin_function_or_method
In [10]:
l.insert(3, 13)
In [11]:
l
Out[11]:
[1, 2, 3, 13, 4, 5, 6, 7, 8, 9, 10]
In [12]:
l.extend?
Signature: l.extend(iterable, /) Docstring: Extend list by appending elements from the iterable. Type: builtin_function_or_method
In [13]:
l.extend([11, 12])
In [14]:
l
Out[14]:
[1, 2, 3, 13, 4, 5, 6, 7, 8, 9, 10, 11, 12]