0% found this document useful (0 votes)
44 views7 pages

List Functions

Uploaded by

sonia shalini
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
44 views7 pages

List Functions

Uploaded by

sonia shalini
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 7

List Functions

Pythonalsooffersmanybuilt-infunctionsandmethodsforlistmanipulation.Thesecanbe applied to
list as per following syntax :

<listobject>.<method name>()

Method Description Example


len() Returnsthelengthofthelistpassedastheargu >>>list1=[10,20,30,40,50]
ment >>>len(list1)
5
list() Createsanemptylistifnoargumentispassed >>>list1=list()
>>> list1[]

>>>str1='aeiou'
Createsalistifasequenceispassedasanargume >>>list1=list(str1)
nt >>>list1
['a','e','i','o','u']
append() Appendsasingleelementpassedasanargume >>>list1=[10,20,30,40]
ntattheendofthelist >>>list1.append(50)
>>>list1
Alistcanalsobeappendedasanelementtoanexi [10,20,30,40,50]
stinglist >>>list1=[10,20,30,40]
>>>list1.append([50,60])
>>>list1
[10,20,30,40,[50,60]]
insert() Insertsanelementataparticularindex inthelist >>>list1=[10,20,30,40,50]
#insertselement25atindexvalue2
>>>list1.insert(2,25)
>>>list1
[10,20,25,30,40,50]
>>>list1.insert(0,100)
>>>list1
[100,10,20,25,30,40,50]
count() Returns the number of timesa >>>list1=[10,20,30,10,40,10]
givenelementappearsinthelist >>> list1.count(10)
3
>>> list1.count(90)
0

remove() Removes the given element from >>>list1=[10,20,30,40,50,30]


thelist.Iftheelementispresentmultipletimes >>>list1.remove(30)
,onlythefirstoccurrenceisremoved.Iftheele >>>list1
mentisnotpresent,thenValue [10,20,40,50,30]
Errorisgenerated >>> list1.remove(90)
ValueError: list.remove(x)
x not in list
pop() Returnstheelementwhoseindexispassedasa >>>list1=[10,20,30,40,50,60]
rgumenttothisfunctionandalsoremovesitfr >>>list1.pop(3)
omthelist.Ifno argument 40
isgiven,thenitreturnsandremovesthelastele >>>list1
mentofthelist [10,20,30,50,60]
>>>list1=[10,20,30,40,50,60]
>>>list1.pop()
60
>>>list1
[10,20,30,40,50]
reverse() Reverses >>>list1=[34,66,12,89,28,99]
theorderofelementsinthegivenlist >>>list1.reverse()
>>>list1
[99,28,89,12,66,34]
>>> list1 = [ 'Tiger' ,'Zebra' ,'Lion','Cat','Elephant','Dog']
>>>list1.reverse()
>>>list1
['Dog', 'Elephant', 'Cat', 'Lion','Zebra','Tiger']

sort() Sorts the elementsofthegivenlistinplace >>>list1=['Tiger','Zebra','Lion','Cat','Elephant','Dog']


>>>list1.sort()
>>>list1
['Cat', 'Dog', 'Elephant', 'Lion','Tiger','Zebra']
>>>list1=[34,66,12,89,28,99]
>>>list1.sort(reverse=True)
>>>list1[99,89,66,34,
28,12]
min() Returns minimum or smallest element of >>>list1=[34,12,63,39,92,44]
the li st >>> min(list1)
12
max() Returnsmaximumorlargestelementofthelist >>>
max(list1)92
sum() Returnssumoftheelementsofthelist >>>sum(list1)
284

CREATINGADICTIONARY

2 | Page
To create a dictionary, the items entered are
Separated by commas and enclosedincurlybraces. Each item is a key value pair, separated through
colon (:).

#dict1isanemptydictionary
>>>dict1={}
>>>dict1 {}

#dict3isthedictionarythatmapsnamesofthestudentstomarksinpercentage
>>>dict3={'Mohan':95,'Ram':89,'Suhel':92,'Sangeeta':85}
>>>dict3
{'Mohan':95,'Ram':89,'Suhel':92,'Sangeeta':85}

ACCESSINGITEMSINADICTIONARY

Theitemsofadictionaryareaccessed viathekeys.Each key serves as the index and maps toavalue.


<dict>[<key>]
>>> dict3 = {'Mohan':95,'Ram':89,'Suhel':92,'Sangeeta':85}
>>> dict3['Ram']
89
Intheaboveexamplesthekey'Ram'alwaysmapstothevalue89

* If the key is notpresentinthedictionarywegetKey Error.

3 | Page
MEMBERSHIPOPERATION

The membership operator IN


checksifthekeyispresentinthedictionaryandreturnsTrue,elseitreturnsFalse.

>>> dict1 = {'Mohan':95,'Ram':89,'Suhel':92,'Sangeeta':85}


>>> 'Suhel' in dict1
True

ThenotinoperatorreturnsTrueifthekeyisnot presentinthedictionary,elseitreturnsFalse.

ADDINGANEWITEM

Wecanaddanewitemtothedictionaryasshowninthefollowingexample:

>>> dict1 = {'Mohan':95,'Ram':89,'Suhel':92,'Sangeeta':85}


>>>dict1['Meena']=78
>>>dict1
{'Mohan':95,'Ram':89,'Suhel':92,'Sangeeta':85,'Meena':78}

UPDATINGANEXISTINGITEM

Theexistingdictionarycanbemodifiedbyjustoverwriting the key-value pair.

>>> dict1 = {'Mohan':95,'Ram':89,'Suhel':92,'Sangeeta':85}


#MarksofSuhelchangedto93.5
>>>dict1['Suhel']=93.5
>>>dict1
{'Mohan':95,'Ram':89,'Suhel':93.5, 'Sangeeta':85}

TRAVERSINGA DICTIONARY

We can access each item of the dictionary or traverse adictionaryusingforloop.

>>> dict1 = {'Mohan':95,'Ram':89,'Suhel':92, ‘’ Sangeeta':85}


Method1:
>>>forkeyindict1:
print (key,':',dict1[key])
Mohan:95
Ram :89
Suhel:92
Sangeeta:85

4 | Page
Method2:

>>> for key,value in dict1.items():


print(key,':',value)
Mohan:95
Ram:89
Suhel:92
Sangeeta:85

DELETING ELEMENT
We can remove an item from the existing dictionary by using del command or using pop()
1. Using del command- The keyword del is used to delete the key present in the dictionary. If the
key is not found, then it raises an error.
del <dict>[key]
2. Using pop() method – pop() method will not delete the item specified by the key from the
dictionary but also return the deleted value.
<dict>.pop(key)
3. popitem()- It returns and removes the last inserted item from dictionary
<dict>.popitem()

5 | Page
DICTIONARYMETHODS ANDBUILT-IN FUNCTIONS

Python provides many functions to work on dictionaries.

Method Description Example


dict() Creates a dictionary from pair1=[('Mohan',95),('Ram',89),
asequenceofkey-valuepairs ('Suhel',92),('Sangeeta',85)]
>>>pair1 [('Mohan',95),
('Ram',89),('Suhl',
92),('Sangeeta',85)]
>>>dict1=dict(pair1)
>>>dict1
{'Mohan':95,'Ram':89,'Suhel':92,
'Sangeeta':85}
len() Returns the length or number >>> dict1 =
ofkey: value pairs of the {'Mohan':95,'Ram':89,'Suhel':92,'Sangeeta':85
dictionarypassedastheargument
}
>>>len(dict1)
4
keys() Returnsalistofkeysinthedictionar >>> dict1 = {'Mohan':95,
y 'Ram':89,'Suhel':92,'Sangeeta':85}
>>>dict1.keys()
dict.keys(['Mohan', 'Ram', 'Suhel', ‘ Sangeeta'])

values() Returnsalistofvaluesinthedictiona >>> dict1 = {'Mohan':95,


ry 'Ram':89,'Suhel':92,'Sangeeta':85}
>>> dict1.values()
dict.values([95,89,92,85])
items() Returnsalistoftuples(key— >>> dict1 = {'Mohan':95,
value)pair 'Ram':89,'Suhel':92,'Sangeeta':85}
>>>dict1.items()
Dict.items([('Mohan',95),('Ram',89),
('Suhel',92),('Sangeeta',85)])
get() Returnsthevaluecorrespondingto >>> dict1 = {'Mohan':95,
thekeypassedastheargument 'Ram':89,'Suhel':92,'Sangeeta':85}
>>> dict1.get('Sangeeta')85
Ifthekeyisnotpresentinthedictiona
ryitwillreturnNone

update() appends thekey-value pair >>> dict1 = {'Mohan':95,


ofthedictionarypassedastheargu 'Ram':89,'Suhel':92,'Sangeeta':85}
ment to the key-value pair >>>dict2={'Sohan':79,'Geeta':89}
ofthegivendictionary
>>>dict1.update(dict2)
>>>dict1
{'Mohan':95,'Ram':89,'Suhel':92,
6 | Page
'Sangeeta':85,'Sohan':79,'Geeta':89}
>>>dict2
{'Sohan':79,'Geeta':89}
clear() Deletesorclearalltheitems >>> dict1 =
ofthedictionary {'Mohan':95,'Ram':89,'Suhel':92,'Sangeeta':85
}
>>>dict1.clear()
>>>dict1
{}
del() Deletestheitemwiththegivenkey >>> dict1 =
Todeletethedictionaryfromthem {'Mohan':95,'Ram':89,'Suhel':92,'Sangeeta':85
emorywewrite:
}
delDict_name
>>>deldict1['Ram']
>>>dict1
{'Mohan':95,'Suhel':92,'Sangeeta':85}

7 | Page

You might also like