Adding items or elements to the list :
append() : add new item at the end
insert() : add new item at specific place in the list
extend() : add the multiple items at the end of the list
Using append()
my_list=['a', 'b']
my_list.append('c')
print(my_list)
Explanation
- my_list = ['a', 'b']: In this line of code, we create a list named my_list with items: 'a' and 'b'.
- my_list. append ('c'): In this code line, we use the append method to add a new item 'c' at the end of my_list.
- print (my_list): This line prints the list.
Output :
['a', 'b', 'c']
Using insert()
After running the code, the output displayed on the console will be ['a',
'b', 'c']. Note that 'b' is now at index 1 in the list and right between 'a'
and 'c'. The list item 'c' which was at index 1 previously now has index
2.
my_list = ['a', 'c']
my_list.insert(1,'b')
print(my_list)
Output:
['a', 'b', 'c']
Out of range
my_list = ['a', 'bʼ]
my_list.insert(5,'c')
print(my_list)
Output :
['a', 'b', 'c']
- my_list =['a', 'b']: Here, we're creating a list named my_list with two elements: 'a' and 'b'.
- my_list. insert (5, 'c'): We're inserting the element 'c' at index 5, which is beyond length of the list.
- print (my_list): This prints out the updated list.
extend()
my_list = ['a', 'b']
my_list.extend(['c', 'd'])
print(my_list)
- my_list = ['a', 'b']: We make a list named my_list with items 'a' and 'b'.
- my_list. extend (['c', 'd']): In this code line, we use the extend method to add multiple items ('c' and 'd') to the end of the list.
- print (my_list): This line prints the updated list.
Output :
['a', 'b', 'c', 'd']
- You have to must try in your python compiler use idle avoid online compilers to Errors
0 Comments