Download as pptx, pdf, or txt
Download as pptx, pdf, or txt
You are on page 1of 12

Collections in Python

List Tuple Set Dictiona


ry
[] () {} {‘key’:values}

Indexing preserved, Indexing preserved, No Indexing, No Indexing,


heterogeneous data Heterogeneous data heterogeneous data heterogeneous data

Mutable Immutable Mutable Mutable

Duplicates allowed, Duplicates allowed, Duplicates not allowed, Duplicate Key not
Size dynamic Size fix Size dynamic allowed, size dynamic

[1,3,”Ram”,10.3] (3,4,”Shukla”) {22,25,14,21,5} {‘Navin’:’Samsung’,


‘Rahul’:’oneplus’}
Tuple Creation
T = ()
T = (10,)
T = 10,20,30 or (10,20,30)

Print(t[0]) -> 10
Print (t[-1]) -> 30
Print(t[1:3]) -> 20,30
#wap to take a Tuple of Numbers from keyboard and
Print its Sum and Average?
t = eval(input(“enter tuple of numbers:”))
l = len(t)
Sum = 0
For x in t:
sum = sum +x

Print(“The Sum =“,sum)


Print(“The Average=“,sum/l)
S = set() -> creation of blank set
Set
S = {0,1,3,4}

#add()
s.add(40) -> {0,1,3,4,40}

#update(x,y,z)

s.update(10,20,30)
Print(s) -> {0,1,3,4,30,10,20}
#wap to eliminate the duplicates from a list
● L = eval(input(“enter list of values:”))
● S = set(l)
● Print(s)
Dictionary
● d = {} or d = dict()
● d[100] = “ravi”
● d[200] = “rahul”
● d[300] = “amit”

● print(d) -> {100:’ravi’, 200:’rahul’, 300:’amit’}


● d = {key:value, key:value}
● d.keys() -> dict_keys([100,200,300])
● d.values() -> dict_values([‘ravi’,’Rahul’,’amit’])

● d[key] -> value


● d.get(key) -> value
#wap to take input name and % of marks of students
in a dictionary and Display the information.
rec={}
n=int(input(“Enter number of students”))
i=1
while i <= n:
name=input(“Enter Student Name))
marks=input(“Enter % of Marks of Student”))
rec[name]=marks
i=i+1
for x in rec:
print(x,rec[x])
Items()
D = {100: ‘ravi’, 200: ’Rahul’, 300: ’amit’}
For k,v in d.items():
print(k,”—”,v)
Operations on DICTIONARY
 d = {1:’a’, 2:’b’, 3:’c’}
 d.clear() -> To remove all entries from the dictionary
 del d -> to delete total dictionary. Now we cannot access d.
 len() -> Returns the number of items in the dictionary
 d.get(key) -> returns the value of that key, if key not presents returns
NONE
 d.get(key,defaultValue)
If the key is present returns the corresponding value otherwise returns
t the Default value
 d.keys() -> it returns all keys associated with dictionary
 d.values() -> it returens all the values of the dictionary
#wap to take Dictionary as input and print the
sum of values

D = eval(input(“Enter dictionary:”))
S = sum(d.values())
Print(“sum = “,s)
#Wap to check the number of occurrence of each
character.
word=input(“Enter any word”)
d={}
for x in word:
d[x]=d.get(x,0)+1

for k,v in d.items():


print(k,”occurred”,v,”times”)
#Wap to take string from user and check the
occurrences of vowels
word=input(“Enter any word”)
vowels={‘a’,’e’,’I’,’o’,’u’}
d={}
for x in word:
if x in vowels:
d[x]=d.get(x,0)+1
for k,v in sorted(d.items()):
print(k,”occurred”,v,”times”)

You might also like