13 List Functions
13 List Functions
1. append()
syntax:
list_name.append(item)
In [6]:
lst = []
lst.append(100)
lst.append(200)
print(lst)
[100, 200]
In [5]:
lst1 = [1,2,3,4]
lst1.append(5)
lst1.append(6)
print(lst1)
[1, 2, 3, 4, 5, 6]
In [8]:
lst3 =[]
for i in range(1,101):
if i % 10 ==0:
lst3.append(i)
print(lst3)
[10, 20, 30, 40, 50, 60, 70, 80, 90, 100]
In [9]:
list1 = [1,2,3,4]
list2 = [5,6,7,8]
list1.append(list2)
print(list1)
list1[4][:3]
Out[16]:
[5, 6, 7]
2. insert()
syntax:
list_name.insert(index,value)
In [2]:
list1 = [1,34,55,10,3,5.6]
list1.insert(3,100)
list1
Out[2]:
In [3]:
list1 = [1,34,55,10,3,5.6]
list1.insert(6,100)
list1
Out[3]:
In [4]:
list1 = [1,34,55,10,3,5.6]
list1.insert(20,300)
list1
Out[4]:
list1 = [1,34,55,10,3,5.6]
list1.insert(-20,300)
list1
Out[5]:
In [7]:
list1 = [1,34,55,10,3,5.6]
list1.insert(-2,300)
list1
Out[7]:
3. extend()
syntax:
list_name.extend(sequence/list)
In [8]:
list1 = [1,2,3,4]
list2 = [5,6,7,8]
list1.extend(list2)
list1
Out[8]:
[1, 2, 3, 4, 5, 6, 7, 8]
In [9]:
str1 = 'Python'
list1 = [1,2,3,4]
list1.extend(str1)
list1
Out[9]:
4. remove()
syntax:
list_name.remove(item)
In [12]:
list1 = [1,34,55,10,3,5.6]
print(list1)
list1.remove(55)
print(list1)
In [13]:
list1 = [1,34,55,10,3,5.6,10]
print(list1)
list1.remove(10)
print(list1)
In [14]:
list1 = [1,34,55,10,3,5.6]
print(list1)
list1.remove(550)
print(list1)
--------------------------------------------------------------------------
-
ValueError Traceback (most recent call las
t)
~\AppData\Local\Temp\ipykernel_13104\1938206938.py in <module>
2 print(list1)
3
----> 4 list1.remove(550)
5 print(list1)
5. pop ()
It is also used for remove items from list, but it will remove last item only and only this function, return
removed value.
syntax:
list_name.pop()
In [16]:
list1 = [1,34,55,10,3,5.6]
list1.pop()
Out[16]:
5.6
In [17]:
list1
Out[17]:
In [18]:
list1.pop()
Out[18]:
In [19]:
list1
Out[19]:
In [20]:
list1 = [1,34,55,10,3,5.6]
list1.pop(2)
Out[20]:
55
6. clear()
syntax:
list_name.clear()
In [21]:
list1 = [1,34,55,10,3,5.6]
list1.clear()
list1
Out[21]:
[]
7. Copy()
syntax:
list1 = list2.copy
In [40]:
list1 = [1,34,55,10,3,5.6]
list2
Out[40]:
In [41]:
list2.remove(10)
In [42]:
list1
Out[42]:
In [43]:
list1 = [1,34,55,10,3,5.6]
list2
Out[43]:
list2.remove(10)
In [45]:
list1
Out[45]:
Shallow copy :
- The changes made in the copied object also reflected in original obje
ct.
- In shallow copy ,a copy of original object is stored and only the ref
erence address is finally copied.
Deep copy :
8. reverse()
syntax:
list_name.reverse()
In [46]:
list1 = [1,2,3,4,5,6,'FUEL',12.4,5]
list1.reverse()
list1
Out[46]:
9. sort()
Syntax:
list_name.sort(reverse = True / False)
In [47]:
list1 = [1,2,4,5,3,2,1,7,4,5,9,3,4,8]
list1.sort()
list1
Out[47]:
[1, 1, 2, 2, 3, 3, 4, 4, 4, 5, 5, 7, 8, 9]
In [48]:
list1 = [1,2,4,5,3,2,1,7,4,5,9,3,4,8]
list1.sort(reverse = True)
list1
Out[48]:
[9, 8, 7, 5, 5, 4, 4, 4, 3, 3, 2, 2, 1, 1]
In [ ]: