Adding an element to the list
We can add elements to the list using append, insert and extend functions.
#Initializing empty list
alist = []
Append function
It is used to add elements at the end of the list.Append function takes only one argument at a time i.e using append function we can add only one element at a time.
#Adding element in the list using append function
alist.append(1)
alist.append(3)
alist.append(5)
print('List after addition of 3 elements : ', alist )
Output :
Insert function
It is used to add an element at the specified index position of the list.
#Adding an element at a specific index using insert function.
alist.insert(1,2)
print('List after performing insert operation : ' , alist)
#Here we are adding element 2 at index position 1
Output :
Extend function
It is used to add a sequence of elements to the list.This function adds elements at the end of a list.
Extend function takes a list of elements as the argument.
#Adding multiple elements to the list
alist.extend( [ 4 , 'python' , 8.97 , (91,90,89) ] )
print('List after performing extend operation : ' , alist)
#Here we are adding elements 4 , ' python ',8.97 and tuple (91,90,89)
Output :
No comments:
Post a Comment