How to add elements in list in Python
In this article, we will some methods through which we can add elements in list.
append()
This list method add a single element in the end of the list. It can be number, string or another list.
Length of the list is incremented after each append.
Syntax: list_name.append(object)
object – can be number, string or another list
li = [1, 2, 3, 4] li.append(5) print(li) li.append('six') print(li) li.append([1, 2]) print(li)
Output:
[1, 2, 3, 4, 5] [1, 2, 3, 4, 5, 'six'] [1, 2, 3, 4, 5, 'six', [1, 2]]
extend()
This method adds all the elements of an iterable(list, tuple, string etc.) to the end of the list
Syntax: list_name.extend(iterable)
li = [1, 2, 3] #adding list li2 = [4, 5] li.extend(li2) print(li) #adding tuple t = (6, 7) li.extend(t) print(li) #adding set s = {8, 9} li.extend(s) print(li)
Output:
[1, 2, 3, 4, 5] [1, 2, 3, 4, 5, 6, 7] [1, 2, 3, 4, 5, 6, 7, 8, 9]
Subscribe
Login
Please login to comment
0 Discussion