Syntax :
list_name.pop(index)
Parameter :
index ( optional ) - The value at index is popped out and removed. If the index is not given, then the last element is popped out and removed.
list Exception : Code # 1: When index is out of range, it returns IndexError
|
Output:
6 New List after pop: [1, 2, 3, 4, 5] 4 (’cat’,’ bat’) 3 New List after pop: [1, 2]
Code # 2:
Output:
6 [1, 2, 3, 4, 5] 1 [2, 3, 4, 5]
Code # 3: IndexError
|
Output:
Traceback (most recent call last): File "/home/1875538d94d5aecde6edea47b57a2212.py", line 5, in print (list1.pop (8)) IndexError: pop index out of range
Practical example: Output:
The fruit list contains fruit_name and a property that speaks about its fruit. The other list contains two juices and is . With pop () and # Python3 program demonstrating
# practical use of the pop () list
fruit
=
[[
’Orange’
,
’ Fruit’
], [
’Banana’
,
’Fruit’
], [
’ Mango’
,
’ Fruit’
]]
consume
=
[
’ Juice’
,
’Eat’
]
possible
=
[]
# Loop through an item in the fruit list
for
item
in
fruit:
# Heavy list use consume
for
use
in
consume:
item.append (use)
result.append (item [:])
item.pop (
-
1
)
print
(result)
[[’Orange’,’ Fruit’, ’Juice’], [’ Orange’, ’Fruit’,’ Eat’], [’Banana’,’ Fruit’, ’Juice’], [’ Banana’, ’ Fruit’, ’Eat’], [’ Mango’, ’Fruit’,’ Juice’], [’Mango’,’ Fruit’, ’Eat’]]