Lecture On List Tuple Set Dictionary
Lecture On List Tuple Set Dictionary
There are four collection data types in the Python programming language:
List is a collection which is ordered and changeable. Allows duplicate members. Tuple is a collection
which is ordered and unchangeable. Allows duplicate members. Set is a collection which is unordered
and unindexed. No duplicate members. Dictionary is a collection which is unordered, changeable and
indexed. No duplicate members.
List
4
25
[4, 9]
[9, 16, 25]
[1, 4]
[9, 16, 25]
Creating Sublist.
Before:
[1, 4, 9, 16, 25, 36, 48, 64]
After:
[1, 4, 9, 16, 25, 36, 49, 64]
Elements can be removed either based on position or based on value. Removing based on index:
list.pop(index), (returns the value removed) del list[index] (do not return the value which is removed)
Remove based on value: remove the first occurance of a specific value list.remove(value)
In [15]: x=5
del x
print(x)
---------------------------------------------------------------------------
NameError Traceback (most recent call last)
Input In [15], in <cell line: 3>()
1 x=5
2 del x
----> 3 print(x)
---------------------------------------------------------------------------
ValueError Traceback (most recent call last)
Input In [18], in <cell line: 2>()
1 squares=[1, 4, 9, 16, 25, 36, 9, 64]
----> 2 squares.remove(7) # Attempting To remove an elelment not present in the list
3 print("After remove element 7:",squares)
Functions that operate on many collections (including list) list: len(),min(), max(), sorted(), sum(), etc.
Length 8
Min: 1
Max: 64
Sum of the list: 204
Sorted [1, 4, 9, 16, 25, 36, 49, 64]
Original List [16, 4, 9, 1, 25, 36, 49, 64]
Copying Lists.
y[3]=2
print("X=",x)
print("Y",y)
print("Address of x:",id(x))
print("Address of y:",id(y))
X= [1, 4, 9, 2, 25]
Y [1, 4, 9, 2, 25]
Address of x: 1688410529472
Address of y: 1688410529472
slicing syntax: list[start:end:step_size] A new list created by collecting elements starting from 'start',
ending at: 'end-1', by incrementing the index by the 'step_size'. If the 'end' can not be reached by
starting from 'start' and applying 'step_size' each time then empty list is returned. When an invalid index
used, empty list is retunred.
In [31]: a=[1,2,3,4,5,6,7,8,9]
print(a[1:7:2])
print(a)
[2, 4, 6]
[1, 2, 3, 4, 5, 6, 7, 8, 9]
In [32]: a=[1,2,3,4,5,6,7,8,9]
print(a[8:0:-1])
print(a)
[9, 8, 7, 6, 5, 4, 3, 2]
[1, 2, 3, 4, 5, 6, 7, 8, 9]
In [33]: a=[1,2,3,4,5,6,7,8,9]
print(a[8::-1])
print(a)
[9, 8, 7, 6, 5, 4, 3, 2, 1]
[1, 2, 3, 4, 5, 6, 7, 8, 9]
Reverse a list.
In [34]: a=[1,2,3,4,5,6,7,8,9]
print(a[::-1])
print(a)
[9, 8, 7, 6, 5, 4, 3, 2, 1]
[1, 2, 3, 4, 5, 6, 7, 8, 9]
In [35]: a=[1,2,3,4,5,6,7,8,9]
print(a[9:12])
[]
In [36]: print(a[7:2])
[]
In [37]: print(a[7:2:-1])
[8, 7, 6, 5, 4]
In [38]: x=[1,2,3]
y=[4,5,6]
x.extend(y)
print(x)
print(y)
[1, 2, 3, 4, 5, 6]
[4, 5, 6]
Tuple
A tuple is a collection which is ordered and not changeable. In Python tuples are written with round
brackets.
21
Chennai
Tuple unpacking
x is: Ravi
y is: 21
z is: Chennai
Extracting sublist
(21, 'cherry')
(21, 'cherry')
('cherry', 21)
()
('cherry', 21)
workaround to change a tuple. create list from tuple. change the list. create tuple from the list.
Functions that operate on many collections (including tuple) list: len(),min(), max(), sorted(), sum(), etc. If
these operations are not applicable we will get an error.
Length 8
Min: 1
Max: 64
Sum of the list: 204
Sorted [1, 4, 9, 16, 25, 36, 49, 64]
Original List (16, 4, 9, 1, 25, 36, 49, 64)
Tuple with single element (special syntax). Regular syntax can be intepreted as unpacking.
t= 123 x= abc
In [50]: t = ('125')
print(type(t))
<class 'str'>
In [51]: t = (1+2*3)
print(type(t))
<class 'int'>
In [52]: t = ('125',)
print(type(t))
<class 'tuple'>
A tuple can contain mutble elements (for example list) and their content can change over time. Once a
tuple is defined, the id() of each member of the tuple is fixed. Any attempt to change the id() of a
member is not allowed.
In [53]: t=(1,'abc',5.6)
t[1]='xyz'
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
Input In [53], in <cell line: 2>()
1 t=(1,'abc',5.6)
----> 2 t[1]='xyz'
In [54]: t=(1,'abc',[1,2])
print("Tuple before:",t)
l=t[2]
print("Address of 3rd element:",id(t[2]))
l.append(3)
print("Tuple after:",t)
print("Address of 3rd element:",id(t[2]))
In [55]: t=(1,'abc',[1,2])
t[2]=[3,4]
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
Input In [55], in <cell line: 2>()
1 t=(1,'abc',[1,2])
----> 2 t[2]=[3,4]
Set
A set is a collection which is unordered and unindexed, duplicates not allowed. In Python sets are written
with curly brackets.
In [58]: l = ["a","b","a"]
s = set(l)
print(s)
{'b', 'a'}
In [60]: s = {'b','a','d','c'}
t = tuple(s)
l2 = list(s)
print(s)
print(t)
print(l2)
KeyError: 'banana'
In [66]: s1 = { "orange","cherry","apple"}
x = s1.pop()
print("Removed:",x)
print("The set becomes:",s1)
x = s1.pop()
print("Removed:",x)
print("The set becomes:",s1)
Removed: cherry
The set becomes: {'apple', 'orange'}
Removed: apple
The set becomes: {'orange'}
s3 = s1.union(s2)
# s3 = s1 | s2 # is also same
print("S1:",s1)
print("S2:",s2)
print("S3:",s3)
In [70]: s1 = { "orange","banana"}
s2 = {"apple", "orange","banana", "cherry"}
s3 = {"apple","1", "2","3"}
print("S1:",s1)
print("S2:",s2)
print("S3:",s3)
print( "S1 is subset of S2?:",s1.issubset(s2) )
#print( "S1 is subset of S2?:",s1 <= s2 )
In [71]: s1 = { "orange","banana"}
s2 = {"apple", "orange","banana", "cherry"}
s3 = { "banana", "orange"}
print( "S1 equals to S2?:",(s1 == s2) )
print( "S1 equals to S3?:",(s1 == s3) )
print( "S1 not equals to S2?:",(s1 != s2) )
print( "S1 not equals to S3?:",(s1 != s3) )
print( "S1 is proper subset of S2?:",s1 < s2 )
print( "S1 is proper superset of S3?:",s1 > s3 )
Functions that operate on many collections (including tuple) list: len(),min(), max(), sorted(), sum(), etc. If
these operations are not applicable we will get an error.
Length: 5
Min: apple
Max: papaya
Sorted : ['apple', 'banana', 'cherry', 'orange', 'papaya']
In [74]: l = ["a","b","a"]
s = set(l)
t = tuple(s)
l2 = list(s)
print(s)
print(t)
print(l2)
{'b', 'a'}
('b', 'a')
['b', 'a']
Dictionary
A dictionary is a collection which is unordered, changeable and indexed. In Python dictionaries are
written with curly brackets, and they have key-value pairs.
defining a dictionary
In [75]: st1 = {
"name": "Ravi",
"age": 21,
"branch": "Chemical"
print(st1)
Possible keys: any immutable object (string, integer/float, tuple-must contain immutable elements only)
can be a key
In [76]: l=[]
st1 = {
"name": "Ravi",
123: "Text",
3.5 : "t2",
"True": [1,2,3],
('abc',123) : [123,45]
print(st1)
{'name': 'Ravi', 123: 'Text', 3.5: 't2', 'True': [1, 2, 3], ('abc', 123): [123, 45]}
Access value of a given key. Can be accessed by passing string as index or using get(key) method.
In [77]: st1 = {
"name": "Ravi",
"age": 21,
"branch": "Chemical",
}
name1 = st1["name"]
age1 = st1["age"]
branch1 = st1["branch"]
print(name1,age1,branch1)
name1 = st1.get("name")
age1 = st1.get("age")
branch1 = st1.get("branch")
print(name1,age1,branch1)
Ravi 21 Chemical
Ravi 21 Chemical
In [78]: st1 = {
123: "Text",
('abc',123) : [123,45]
}
indexedBy123 = st1[123]
indexedByTuple= st1[('abc',123)]
print("Index by int:",indexedBy123,"Index by tuple:",indexedByTuple)
indexedBy123 = st1.get(123)
indexedByTuple= st1.get(('abc',123))
print("Index by int:",indexedBy123,"Index by tuple:",indexedByTuple)
In [79]: st1 = {
"name": "Ravi",
"age": 21,
"branch": "Chemical"
}
Add/modify one are more new name-value pairs. If the key is not present in the dictionary the pair will
be added. OW the value of that key changed.
st1["age"]=20
st1["hostler"]="Yes"
print("After:",st1)
print("After:",st1)
print("After:",st1)
In [84]: st1 = {
"name": "Ravi",
"age": 21,
"branch": "Chemical"
}
print(len(st1))
print(st1)
print(st1)
3
{'name': 'Ravi', 'age': 21, 'branch': 'Chemical'}
---------------------------------------------------------------------------
KeyError Traceback (most recent call last)
Input In [84], in <cell line: 10>()
7 print(len(st1))
8 print(st1)
---> 10 flag = st1.pop("hostler") #raises an error if the key is not present
12 #del st1["hostler"] #raises an error if the key is not present
14 na = st1["NAME"] # keys are case sensitive
KeyError: 'hostler'
Finding all the key names, values, all name-value pairs in a list.
In [85]: st1 = {
"name": "Ravi",
"age": 21,
"branch": "Chemical"
}
print("Keys:",st1.keys())
print("Values:",st1.values())
print("Items:",st1.items())
Nested structures are also possible (e.g tuple as an element inside a list)
Kailash Vizag
('Kailash', 17, 'Vizag')
In [87]: contactnumbers={
'Kailash':['[email protected]', 9786666555],
'Ravi':['[email protected]', 9786666556]
}
contacts = contactnumbers['Kailash']
print(contacts)
['[email protected]', 9786666555]
In [88]: contactnumbers={
'Kailash':{"email":'[email protected]', "phone":9786666555},
'Ravi':{"email":'[email protected]', "phone":9786666556}
}
contacts = contactnumbers['Kailash']
print(contacts)
In [89]: branches={
'SVR':{'Madhurawada'},
'CMR':{ "MVP","GAJUWAKA"},
'SouthIndia':{ "Jagadamba","GAJUWAKA"}
}
cmrBr = branches['CMR']
print("CMR Branches:",cmrBr)
print("\n\nSorted by StoreName:")
sortedKeys = sorted(branches)
print(sortedKeys)
print("\n\n")
key=sortedKeys[0]
print(key,branches[key])
print(sortedKeys[1],branches[sortedKeys[1]])
print(sortedKeys[2],branches[sortedKeys[2]])
Sorted by StoreName:
['CMR', 'SVR', 'SouthIndia']
In [ ]: