Lists in Python — Insertions

A list in Python is a mutable collection of elements. This is the way a list is defined:
Input
lst=[1,”one”,2,”two”]

print (lst)
Output
[1, ‘one’, 2, ‘two’]

Array still indexing is permitted and the indexing starts from 0.

Input
lst=[1,”one”,2,”two”]
print (lst[0])
print (lst[1])
print (lst[3])
Output
1
one
two

The for in loop

Input
lst=[1,2,3,4,5]

for n in lst:
print (n)
Output
1
2
3
4
5

Since the list is mutable, entries can be changed:

Input
lst=[1,2,3,4,5]
print (lst)
lst[3]=”Changed”
print (lst)
Output
[1, 2, 3, 4, 5]
[1, 2, 3, ‘Changed’, 5]

Some methods of the list:

append() adds an element to the end of the list.
Input
lst=[]
lst.append(“One”)
lst.append(“Two”)
lst.append(“Three”)
print (lst)
Output
[‘One’, ‘Two’, ‘Three’]
The insert function inserts data at the given index and shifts everything else rightwards:
Input
lst=[“One”,”Three”,”Five”,”Seven”,”Nine”]
print(lst)
lst.insert(1,”Two”)
print (lst)
lst.insert(3,”Four”)
print(lst)
lst.insert(5,”Six”)
print(lst)
lst.insert(7,”Eight”)
print(lst)

Output
[‘One’, ‘Three’, ‘Five’, ‘Seven’, ‘Nine’]
[‘One’, ‘Two’, ‘Three’, ‘Five’, ‘Seven’, ‘Nine’]
[‘One’, ‘Two’, ‘Three’, ‘Four’, ‘Five’, ‘Seven’, ‘Nine’]
[‘One’, ‘Two’, ‘Three’, ‘Four’, ‘Five’, ‘Six’, ‘Seven’, ‘Nine’]
[‘One’, ‘Two’, ‘Three’, ‘Four’, ‘Five’, ‘Six’, ‘Seven’, ‘Eight’, ‘Nine’]

Lists can be added to lists
Input
lst1=[1,2,3]
lst2=[4,5,6]
lst1.insert(3,lst2)
print(lst1)
Output
[1, 2, 3, [4, 5, 6]]

append function works the same way.
Input
lst1=[1,2,3]
lst2=[4,5,6]
lst1.append(lst2)
print(lst1)
Output
[1, 2, 3, [4, 5, 6]]

+ operator can be used to create a new list
Input
lst1=[1,2,3]
lst2=[4,5,6]
lst1=lst1 + lst2
print(lst1)
Output
[1, 2, 3, 4, 5, 6]

 

 

 

 

 

 

Leave a Reply