List Function
List Function
manipulation.
• The syntax of using list functions is :
• ListObjectName.functionName()
• There are many list functions like:
• index()
• append()
• extend()
• insert()
• pop()
• remove()
• clear()
• count()
• reverse()
• sort()
• This function is used to get the index of first matched item from
the list. It returns index value of item to search.
• For example
>>> L1= [10,20,30,40,50,20]
>>> L1. index (20)
1 # item first matched at index 1
Note: if we pass any element which is not in the list then index
function will return an error: VALUe Error: n is not in the list
>>> L1. index (100) #Error
• This function is used to add items to the end of the list.
• For example
>>> family= [“father”,” mother”,” bro”,” sis”]
>>> family. append(“Tommy”)
>>> family
[“father”,”mother”,”bro”,”sis”,”Tommy”]
Note: append () function will add the new item but not return any value.
Let us understand this:
>>> L1= [10,20,30]
>>> L2=L1.append(40)
>>> L2 # Empty will not store any item of L1
>>> L1
[10, 20, 30, 40]
• This function is also used for adding multiple items. With extend we
can add only “list” to any list. Single value cannot be added using
extend ()
• For example
>>> subject1=["physics","chemistry","cs"]
>>> subject2=["english","maths"]
>>> subject1.extend(subject2)
>>> subject1
['physics', 'chemistry', 'cs', 'english', 'maths']
Note: here subject1 will add the contents of subject2 in it without
effecting subject2
Like append(), extend() also does not return any value.
>>> subject3 = subject1.extend(subject2)
>>>subject3 # Empty
• append () allows to add only 1 items to a list, extend () can add
multiple items to a list.
>>> L1=[10,20,30,40,50]
>>> L1.pop()
50
>>> val = L1.pop(2)
>>> val
30
>>> L1
[10, 20, 40]
>>>
• The pop() method raises an exception(run time error) if the
list is already empty.
>>> L1= [ ]
>>> L1.pop()