Python Collections Tutorial

#Python List
x=[]
x
Output: []
x=[100,12.34,'python',True,100,200,300] 
x
Output: [100, 12.34, 'python', True, 100, 200, 300]
#Accessing individual data item through index value 
x[0]
Output:
100

x[5]
Output: 200

x[6]
Output:300

x[-1]
Output:300

#Length of a List 
len(x)
Output: 
7
import sys
print(sys.getsizeof(x))

112
#Retrieve all data items from a List 
for k in x:
print(k)

100 
12.34 
python 
True
100
200
300
#To get all in built functions in List 
dir(x)

Output:
['__add__',
'__class__',
'__contains__',
'__delattr__',
'__delitem__',
'__dir__',
'__doc__',
'__eq__',
'__format__',
'__ge__',
'__getattribute__',
'__getitem__',
'__gt__',
'__hash__',
'__iadd__',
'__imul__',
'__init__',
'__init_subclass__',
'__iter__',
'__le__',
'__len__',
'__lt__',
'__mul__',
'__ne__',
'__new__',
'__reduce__',
'__reduce_ex__',
'__repr__',
'__reversed__',
'__rmul__',
'__setattr__',
'__setitem__',
'__sizeof__',
'__str__',
'__subclasshook__',
'append',
'clear',
'copy',
'count',
'extend',
'index',
'insert',
'pop',
'remove',
'reverse',
'sort']
help(x.append)

Help on built-in function append:

append(object, /) method of builtins.list instance    
	Append object to the end of the list.
x.append(500) 
x
Output
[100, 12.34, 'python', True, 100, 200, 300, 500]
x.insert(2,600) 
x

Output:
[100, 12.34, 600, 'python', True, 100, 200, 300, 500]
x1=x.copy() 
x1

Output:
[100, 12.34, 600, 'python', True, 100, 200, 300, 500]
x1.clear() 
x1

Output:
[]
x.count(100)

Output:
2
x.count(12.34)

Output:
1
x.index(12.34)

Output:
1
x.index(500)

Output:
8
x.remove(100) 
x

Output:
[12.34, 600, 'python', True, 100, 200, 300, 500]
x.pop() 
x

Output:
[12.34, 600, 'python', True, 100, 200, 300]
x.reverse() 
x

Output:
[300, 200, 100, True, 'python', 600, 12.34]
x1=[30,35,25,15,50] 
x1.sort()
x1

Output:
[15, 25, 30, 35, 50]
x2=[40,50,60]
x1.extend(x2) 
x1

Output:
[15, 25, 30, 35, 50, 40, 50, 60]
#Python Set
fruits={"apple","banana","cherry","orange","apple"} 
print(fruits)

Output:
{'banana', 'apple', 'orange', 'cherry'}
#length of Set 
len(fruits)

Output:
4
import sys
print(sys.getsizeof(fruits))

Output:
216
#Retrieve all data items from fruits
for k in fruits:
	print(k)

Output:
banana
apple 
orange 
cherry
#Create a Set by invoking set()
s1=set()
s1

Output:
set()
#To get all inbuilt function in Set 
dir(s1)

Output:
['__and__',
'__class__',
'__contains__',
'__delattr__',
'__dir__',
'__doc__',
'__eq__',
'__format__',
'__ge__',
'__getattribute__',
'__gt__',
'__hash__',
'__iand__',
'__init__',
'__init_subclass__',
'__ior__',
'__isub__',
'__iter__',
'__ixor__',
'__le__',
'__len__',
'__lt__',
'__ne__',
'__new__',
'__or__',
'__rand__',
'__reduce__',
'__reduce_ex__',
'__repr__',
'__ror__',
'__rsub__',
'__rxor__',
'__setattr__',
'__sizeof__',
'__str__',
'__sub__',
'__subclasshook__',
'__xor__',
'add',
'clear',
'copy',
'difference',
'difference_update',
'discard',
'intersection',
'intersection_update',
'isdisjoint',
'issubset',
'issuperset',
'pop',
'remove',
'symmetric_difference',
'symmetric_difference_update',
'union', 
'update']
s1.add(100)
s1.add(12.34) 
s1.add('python') 
s1.add(True)
s1.add(100) 
s1.add(200)

print(s1)

Output:
{True, 100, 200, 'python', 12.34}
s2=set([300,400,500,False,'Machine Learning',300]) 
print(s2)

Output:
{False, 300, 'Machine Learning', 400, 500}
s3=s2.copy() 
s3

Output:
{300, 400, 500, False, 'Machine Learning'}
s3.clear() 
s3

Output:
set()
#Remove a data item from a Set 
s2.remove(400)
s2

Output:
{300, 500, False, 'Machine Learning'}
s2.discard(500) 
s2

Output:
{300, False, 'Machine Learning'}
s2.remove(1000) 
s2

 KeyError                            Traceback (most recent call last)
>ipython-input-15-27c63ede71b2> in >module> 
----> 1 s2.remove(1000)
      2 s2

KeyError: 1000
s2.discard(1000) 
s2

Output:
{300, False, 'Machine Learning'}
s2.pop() 
s2

Output:
{300, 'Machine Learning'}
del s2 
s2


 NameError                            Traceback (most recent call last)
>ipython-input-21-9b4ca538b1cf> in >module> 
----> 1 del s2
      2 s2

NameError: name 's2' is not defined
s4=set([10,20,30]) 
s5=set([30,40,50,60])
s4.union(s5)

Output:
{10, 20, 30, 40, 50, 60}
s4.intersection(s5)

Output:
{30}
#Python Tuple
t1=(100,3.4,False,'Deep Learning',3.4,200,300) 
t1

Output:
(100, 3.4, False, 'Deep Learning', 3.4, 200, 300)
len(t1)

Output:
7
t1[0]

Output:
100
t1[-1]

Output:
300
#Retrieve all data items from a Tuple 
for x in t1:
	print(x)

Output:
100
3.4
False
Deep Learning
3.4
200
300
import sys
print(sys.getsizeof(t1))

Output:
96
t2=('a',)
t3=('a','aa')
t4=('a','aa','aaa')

print(t2)
print(t3)
print(t4)

Output:
('a',)
('a', 'aa')
('a', 'aa', 'aaa')
type(t2)

Output:
tuple
type(t4)

Output:
tuple
t5=1, 
t6=1,2 
t7=1,2,3

print(t5)
print(t6)
print(t7)

Output:
(1,)
(1, 2) 
(1, 2, 3)
#Tuple Assignment 
#(regdno,name,branch) 
t8=(101,'Rahul','CSE')

regdno=t8[0] 
name=t8[1] 
branch=t8[2]

print(regdno)
print(name)
print(branch)

Output:
101 
Rahul 
CSE
dir(t1)

Output:
['__add__',
'__class__',
'__contains__',
'__delattr__',
'__dir__',
'__doc__',
'__eq__',
'__format__',
'__ge__',
'__getattribute__',
'__getitem__',
'__getnewargs__',
'__gt__',
'__hash__',
'__init__',
'__init_subclass__',
'__iter__',
'__le__',
'__len__',
'__lt__',
'__mul__',
'__ne__',
'__new__',
'__reduce__',
'__reduce_ex__',
'__repr__',
'__rmul__',
'__setattr__',
'__sizeof__',
'__str__',
'__subclasshook__',
'count',
'index']
t8.index('Rahul')

Output:
1
t8.count(101)

Output:
1
#Python Dictionary
car_detail={"brand":"Maruti","model":"ciaz","year":2018} 
car_detail

Output:
{'brand': 'Maruti', 'model': 'ciaz', 'year': 2018}
#Length of dictionary 
len(car_detail)

Output:
3
#Access a particular value 
car_detail["model"]

Output:
'ciaz'
car_detail.get("model")

Output:
'ciaz'
type(car_detail)

Output:
dict
#To get all keys
car_detail.keys()

Output:
dict_keys(['brand', 'model', 'year'])
#To get all values
car_detail.values()

Output:
dict_values(['Maruti', 'ciaz', 2018])
#To get all pairs
car_detail.items()

Output:
dict_items([('brand', 'Maruti'), ('model', 'ciaz'), ('year', 2018)])
#To change the value 
car_detail["year"]=2020 
car_detail

Output:
{'brand': 'Maruti', 'model': 'ciaz', 'year': 2020}
car_detail.update({"year":2019}) 
car_detail

Output:
{'brand': 'Maruti', 'model': 'ciaz', 'year': 2019}
#Add a new pair
car_detail["color"]="Red" 
car_detail

Output:
{'brand': 'Maruti', 'model': 'ciaz', 'year': 2019, 'color': 'Red'}
car_info=car_detail.copy() 
car_info

Output:
{'brand': 'Maruti', 'model': 'ciaz', 'year': 2019, 'color': 'Red'}
car_info.clear() 
car_info

Output:
{}
#Remove a pair from dictionary 
car_detail.pop("year")
car_detail

Output:
{'brand': 'Maruti', 'model': 'ciaz', 'color': 'Red'}
car_detail.popitem() 
car_detail

Output:
{'brand': 'Maruti', 'model': 'ciaz'}
del car_detail 
car_detail

 NameError                            Traceback (most recent call last)
>ipython-input-16-cca5fb1ffb57> in >module> 
	  1 del car_detail
----> 2 car_detail

NameError: name 'car_detail' is not defined
dict1={"brand":"Honda","model":"Honda City","color":"White"} 
dict1

Output:
{'brand': 'Honda', 'model': 'Honda City', 'color': 'White'}
#Retrieve all pairs from a dictionary 
for x,y in dict1.items():
	print(x,y)

Output:
brand Honda 
model Honda City 
color White
#Another dictionary where a key contains a list of values
emp_detail={'eid':[101,102,103],'ename':['Akshay','Ajay','Abhay'],'esal':[10000,20000,30000 
emp_detail

Output:
{'eid': [101, 102, 103],
	'ename': ['Akshay', 'Ajay', 'Abhay'], 
	'esal': [10000, 20000, 30000]}

About the Author



Silan Software is one of the India's leading provider of offline & online training for Java, Python, AI (Machine Learning, Deep Learning), Data Science, Software Development & many more emerging Technologies.

We provide Academic Training || Industrial Training || Corporate Training || Internship || Java || Python || AI using Python || Data Science etc






 PreviousNext