0% found this document useful (0 votes)
10 views20 pages

Lecture On List Tuple Set Dictionary

The document provides an overview of built-in data structures in Python, focusing primarily on lists. It explains the characteristics of lists, including their ordered and mutable nature, and demonstrates various operations such as element extraction, modification, and list methods. Additionally, it discusses concepts like shallow and deep copying, nested lists, and error handling when manipulating lists.

Uploaded by

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

Lecture On List Tuple Set Dictionary

The document provides an overview of built-in data structures in Python, focusing primarily on lists. It explains the characteristics of lists, including their ordered and mutable nature, and demonstrates various operations such as element extraction, modification, and list methods. Additionally, it discusses concepts like shallow and deep copying, nested lists, and error handling when manipulating lists.

Uploaded by

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

Built-in Data Structures

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

List is a collection which is ordered and changeable. Allows duplicate members.

In [1]: squares = [1, 4, 9, 16, 25]


print(squares)

[1, 4, 9, 16, 25]

Lists might contain items of different types. mutable type

In [2]: employee = [101, 'Chetan', 20, 54000, 7.5]


print(employee)

[101, 'Chetan', 20, 54000, 7.5]

Extracting single element or sub element list


In [3]: squares = [1, 4, 9, 16, 25]
print(squares[1]) #element at index
print(squares[-1]) #element index from back

4
25

Extracting sub element list

In [4]: squares = [1, 4, 9, 16, 25]


print(squares[1:3]) #extract sublist [1,3)
print(squares[-3:]) #extract sublist
print(squares[:-3]) #extract sublist
print(squares[2:]) #extract sublist

[4, 9]
[9, 16, 25]
[1, 4]
[9, 16, 25]

Creating Sublist.

In [5]: squares = [1, 4, 9, 16, 25]


s1=squares[1:3]
print(squares)
print(s1)

[1, 4, 9, 16, 25]


[4, 9]

Sublist elements refer to original list elements

In [6]: squares = [1, 4, 9, 16, 25]


s1=squares[1:3]
print("Second Element of Original list",id(squares[1]))
print("First Element of sub list",id(s1[0]))
print("Third Element of Original list",id(squares[2]))
print("Second Element of sub list",id(s1[1]))

Second Element of Original list 1688294943120


First Element of sub list 1688294943120
Third Element of Original list 1688294943280
Second Element of sub list 1688294943280

In [7]: print("Original list",id(squares))


print("sub list",id(s1))

Original list 1688381814080


sub list 1688381812928
Effect of change in the original list on sublist.

In [8]: squares = [1, 4, 9, 16, 25]


s1=squares[1:3]
print("Before the change.\nFirst Element of sub list at:",id(s1[0]))
print("Second Element of Original list at:",id(squares[1]))
squares[1]=5
print(squares)
print(s1)
print("After the change.\nFirst Element of sub list at:",id(s1[0]))
print("Second Element of Original list at:",id(squares[1]))

Before the change.


First Element of sub list at: 1688294943120
Second Element of Original list at: 1688294943120
[1, 5, 9, 16, 25]
[4, 9]
After the change.
First Element of sub list at: 1688294943120
Second Element of Original list at: 1688294943152

Effect of Modifying extracted sublist items on the original list

In [9]: squares = [1, 4, 9, 16, 25]


s1=squares[1:3]
print(squares)
print(s1)
print("Before the change.\nFirst Element of sub list at:",id(s1[0]))
print("Second Element of Original list at:",id(squares[1]))
s1[0]=5
print(squares)
print(s1)
print("After the change.\nFirst Element of sub list at:",id(s1[0]))
print("Second Element of Original list at:",id(squares[1]))

[1, 4, 9, 16, 25]


[4, 9]
Before the change.
First Element of sub list at: 1688294943120
Second Element of Original list at: 1688294943120
[1, 4, 9, 16, 25]
[5, 9]
After the change.
First Element of sub list at: 1688294943152
Second Element of Original list at: 1688294943120

Adding an element at a specific index


In [10]: squares = [1, 4, 9, 25]
print("Before:",squares)
squares.insert(3,16)
print("After:",squares)

Before: [1, 4, 9, 25]


After: [1, 4, 9, 16, 25]
Adding single element or a list of elements at the end of a list

In [11]: squares = [1, 4, 9, 16, 25]


print("Before Append element:",squares)
squares.append(36) #append an item
print("After Append element:",squares)

y = squares+[49,64] #combine 2 lists and creates a new list.


print("After Append list:",squares)
print("After Append list:",y)

Before Append element: [1, 4, 9, 16, 25]


After Append element: [1, 4, 9, 16, 25, 36]
After Append list: [1, 4, 9, 16, 25, 36]
After Append list: [1, 4, 9, 16, 25, 36, 49, 64]

Calling append with a list.

In [12]: squares = [1, 4, 9, 16, 25]


squares.append([39,49]) #append a sublist as an item
print("After Append element:",squares)

After Append element: [1, 4, 9, 16, 25, [39, 49]]

Replace an element at a specific index.

In [13]: squares=[1, 4, 9, 16, 25, 36, 48, 64]


print("Before:\n",squares)

squares[6]=49 #replace one item


print("After:\n",squares)

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 [14]: squares=[1, 4, 9, 16, 25, 36, 49, 64]


print("Before:",squares)
z = squares.pop(3)
print("\nAfter removing element at index 3:",squares)

print("\n The value removed is:",z)

Before: [1, 4, 9, 16, 25, 36, 49, 64]

After removing element at index 3: [1, 4, 9, 25, 36, 49, 64]

The value removed is: 16

Removing a variable from the current execution context.

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)

NameError: name 'x' is not defined

Another way to remove using index

In [16]: squares=[1, 4, 9, 16, 25, 36, 49, 64]


del squares[5] # To remove elelment at index
print("After removing element at index 5:",squares)

After removing element at index 5: [1, 4, 9, 16, 25, 49, 64]

Remove element by value

In [17]: squares=[1, 4, 9, 16, 25, 36, 9, 64]


squares.remove(9) # To remove elelment by value
print("After remove element 9:",squares)

After remove element 9: [1, 4, 16, 25, 36, 9, 64]

Error cases in removing an element from a list.

In [18]: squares=[1, 4, 9, 16, 25, 36, 9, 64]


squares.remove(7) # Attempting To remove an elelment not present in the list
print("After remove element 7:",squares)

---------------------------------------------------------------------------
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)

ValueError: list.remove(x): x not in list

Wrong index passed for pop

In [19]: squares=[1, 4, 9, 16, 25, 36, 49, 64]


print("Before:",squares)
z = squares.pop(13)
print("\nAfter removing element at index 13:",squares)

print("\n The value removed is:",z)

Before: [1, 4, 9, 16, 25, 36, 49, 64]


---------------------------------------------------------------------------
IndexError Traceback (most recent call last)
Input In [19], in <cell line: 3>()
1 squares=[1, 4, 9, 16, 25, 36, 49, 64]
2 print("Before:",squares)
----> 3 z = squares.pop(13)
4 print("\nAfter removing element at index 13:",squares)
6 print("\n The value removed is:",z)

IndexError: pop index out of range

In [20]: squares=[1, 4, 9, 16, 25, 36, 49, 64]


del squares[15] # To remove elelment at index
print("After removing element at index 15:",squares)
---------------------------------------------------------------------------
IndexError Traceback (most recent call last)
Input In [20], in <cell line: 2>()
1 squares=[1, 4, 9, 16, 25, 36, 49, 64]
----> 2 del squares[15] # To remove elelment at index
3 print("After removing element at index 15:",squares)

IndexError: list assignment index out of range

Modifying/rearranging the elements: sort(), reverse()

In [21]: squares=[4, 9, 1, 16, 25, 36, 49, 64]


print("Before:",squares)
squares.reverse()
print("After Reversing:",squares)
squares.sort()
print("After Sorting:",squares)
squares.sort(reverse=True)
print("After Sorting Desc order:",squares)

Before: [4, 9, 1, 16, 25, 36, 49, 64]


After Reversing: [64, 49, 36, 25, 16, 1, 9, 4]
After Sorting: [1, 4, 9, 16, 25, 36, 49, 64]
After Sorting Desc order: [64, 49, 36, 25, 16, 9, 4, 1]

Functions that operate on many collections (including list) list: len(),min(), max(), sorted(), sum(), etc.

In [22]: squares=[16, 4, 9, 1, 25, 36, 49, 64]


print("Length",len(squares))
print("Min:",min(squares))
print("Max:",max(squares))

print("Sum of the list:",sum(squares))


y2 = sorted(squares)
print("Sorted ",y2)
print("Original List",squares)

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]

A list can also be composed of different data types.

In [23]: student = ['Kailash',17,'Mechanical',True]


print(student)
print(student[0])
m1 = min(student)

['Kailash', 17, 'Mechanical', True]


Kailash
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
Input In [23], in <cell line: 4>()
2 print(student)
3 print(student[0])
----> 4 m1 = min(student)

TypeError: '<' not supported between instances of 'int' and 'str'

In [24]: depts = ['IT','CSE','Mechanical',"Chemical Engineering","PE"]


print(depts)
print(depts[0])
first = min(depts)
print(first)
['IT', 'CSE', 'Mechanical', 'Chemical Engineering', 'PE']
IT
CSE

Copying Lists.

In [25]: x=[1, 4, 9, 16, 25]


y = x;

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

Shallow Copy vs Deep Copy.

In [26]: x=[1, 4, 9, 16, 25]


y = x.copy();
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, 16, 25]


Y [1, 4, 9, 2, 25]
Address of x: 1688410174336
Address of y: 1688410249216

Nested Lists. A list containts another list as an element.

In [27]: x=[1, [4, 36, 49], 9, 16, 25]


In [28]: x=[1, [4, 36, 49], 9, 16, 25]
y = x.copy();
y[1][1]=10
print("X=",x)
print("Y",y)

X= [1, [4, 10, 49], 9, 16, 25]


Y [1, [4, 10, 49], 9, 16, 25]

In [29]: import copy

x=[16, [4, 9, 1], 25, 36, 49, 64]

y = copy.copy(x); #shallow copy


#y = copy.deepcopy(x); # deep copy
y[1][1]=10
print("X=",x)
print("Y",y)

X= [16, [4, 10, 1], 25, 36, 49, 64]


Y [16, [4, 10, 1], 25, 36, 49, 64]

Some of the string operations produce list.

In [30]: x = "It is a hot day!"


a = x.split();
print(a)

['It', 'is', 'a', 'hot', 'day!']

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]

Invalid indices returns empty list.

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]

Extending a list by passing an iterable object.

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]

The Documentation for list is at: https://python-reference.readthedocs.io/en/latest/docs/list/index.html

Tuple
A tuple is a collection which is ordered and not changeable. In Python tuples are written with round
brackets.

In [39]: t1 = ("Ravi", 21, "cherry","Chennai")


print(t1)
t1[1]=5 #error. Not mutable.

('Ravi', 21, 'cherry', 'Chennai')


---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
Input In [39], in <cell line: 3>()
1 t1 = ("Ravi", 21, "cherry","Chennai")
2 print(t1)
----> 3 t1[1]=5

TypeError: 'tuple' object does not support item assignment

Accessing individual elements: by indexes either from front or rear

In [40]: t1 = ("Ravi", 21, "cherry","Chennai")


print(t1[1]) #element at index
print(t1[-1]) #element index from back

21
Chennai

Tuple unpacking

In [41]: t1 = ("Ravi", 21,"Chennai")


x, y, z = t1
print("x is:",x)
print("y is:",y)
print("z is:",z)

x is: Ravi
y is: 21
z is: Chennai

Extracting sublist

In [42]: t1 = ("Ravi", 21, "cherry","Chennai")


print(t1[1:3]) #extract sublist [1,3)
print(t1[-3:-1]) #extract sublist
print(t1[-2:-4:-1]) #extract sublist

(21, 'cherry')
(21, 'cherry')
('cherry', 21)

In [43]: t1 = ("Ravi", 21, "cherry","Chennai")


print(t1[-2:-4]) #extract sublist

()

In [44]: t1 = ("Ravi", 21, "cherry","Chennai")


print(t1[-2:-4:-1]) #extract sublist

('cherry', 21)

workaround to change a tuple. create list from tuple. change the list. create tuple from the list.

In [45]: t1 = ("Ravi", 21, "cherry","Chennai")


t2 = t1
print("Before:",t1)
l1= list(t1) # create a list from a tuple
l1[1]=5 # change list elements
t1 = tuple(l1) # create tuple from list and change the reference to point at the new tuple.
print("After:",t1)
print("Original Tuple:",t2)

Before: ('Ravi', 21, 'cherry', 'Chennai')


After: ('Ravi', 5, 'cherry', 'Chennai')
Original Tuple: ('Ravi', 21, 'cherry', 'Chennai')

count a number of times a value occurs in a tuple

In [46]: t1 = ("Ravi", 21, "cherry","Chennai",21)


print("Number of times 21 occurs:",t1.count(21))
print("Number of times Ravi occurs:",t1.count('Ravi'))

Number of times 21 occurs: 2


Number of times Ravi occurs: 1

In [47]: t1 = ["Ravi", 21, "cherry","Chennai",21]

print("Number of times Ravi occurs:",t1.count('Ravi2'))

Number of times Ravi occurs: 0

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.

In [48]: #squares = ("Ravi", 21, "cherry","Chennai",21)


squares=(16, 4, 9, 1, 25, 36, 49, 64)
print("Length",len(squares))
print("Min:",min(squares))
print("Max:",max(squares))

print("Sum of the list:",sum(squares))


print("Sorted ",sorted(squares))
print("Original List",squares)

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.

In [49]: t,x = (123,'abc')


print("t=",t, "x=",x)

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'

TypeError: 'tuple' object does not support item assignment

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]))

Tuple before: (1, 'abc', [1, 2])


Address of 3rd element: 1688410718848
Tuple after: (1, 'abc', [1, 2, 3])
Address of 3rd element: 1688410718848

Following attempting to change the 3rd element reference.

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]

TypeError: 'tuple' object does not support item assignment

Set
A set is a collection which is unordered and unindexed, duplicates not allowed. In Python sets are written
with curly brackets.

In [56]: fruits = {"apple", "orange", "cherry"}


print(fruits)

{'cherry', 'apple', 'orange'}

Python allows the Set elements can be of different data type.

In [57]: fruits = {"apple", "orange",1, "cherry"}


print(fruits)

{'cherry', 'apple', 'orange', 1}

Creating a Set from a given list.

In [58]: l = ["a","b","a"]
s = set(l)
print(s)

{'b', 'a'}

Creating a Set from a given tuple.


In [59]: t1 = ("a1","b1","c1","b1")
s = set(t1)
print(s)

{'a1', 'c1', 'b1'}

Creating a tuple/list from a given Set.

In [60]: s = {'b','a','d','c'}
t = tuple(s)
l2 = list(s)
print(s)
print(t)
print(l2)

{'b', 'd', 'c', 'a'}


('b', 'd', 'c', 'a')
['b', 'd', 'c', 'a']

Add a new element to a set. Attempt to add duplicate element is ignored

In [61]: fruits = {"apple", "orange","cherry"}


print("Before:",fruits)
fruits.add("mango")
print("After 1st add mango:",fruits)
fruits.add("mango") #duplicate is ignored
print("After the 2nd add mango:",fruits)

Before: {'cherry', 'apple', 'orange'}


After 1st add mango: {'cherry', 'mango', 'apple', 'orange'}
After the 2nd add mango: {'cherry', 'mango', 'apple', 'orange'}

Set Membership check.

In [62]: fruits = {"apple", "orange","cherry"}


isPresent = "orange" in fruits
print("orange is a member of the set:",isPresent)
print("mango is a member of the set:","mango" in fruits)

orange is a member of the set: True


mango is a member of the set: False

Add all elements in a list to a set

In [63]: s1 = {"apple", "orange", "cherry"}


print("Before:",s1)
s1.update(["banana","pinapple"])
print("After update:",s1)

Before: {'cherry', 'apple', 'orange'}


After update: {'apple', 'banana', 'orange', 'cherry', 'pinapple'}

Remove an element options: remove()/discard()/pop()/clear()

Remove an element from a set using: remove()

In [64]: s1 = {"apple", "orange", "cherry"}


print("Before:",s1)
s1.remove("orange") # element exists in the set
print("After removing orange:",s1)
print("\nTrying to remove banana:")
s1.remove("banana") # when the element does not exist in the set, gives an Error

Before: {'cherry', 'apple', 'orange'}


After removing orange: {'cherry', 'apple'}

Trying to remove banana:


---------------------------------------------------------------------------
KeyError Traceback (most recent call last)
Input In [64], in <cell line: 6>()
4 print("After removing orange:",s1)
5 print("\nTrying to remove banana:")
----> 6 s1.remove("banana")

KeyError: 'banana'

Remove an element from a set using: discard()

In [65]: s1 = {"apple", "orange", "cherry"}


print("Before:",s1)
s1.discard("orange") # element exists in the set
print("After removing orange:",s1)
s1.discard("banana") # when the element does not exist in the set, simply ignores.
print("After attempting to remove banana:",s1)

Before: {'cherry', 'apple', 'orange'}


After removing orange: {'cherry', 'apple'}
After attempting to remove banana: {'cherry', 'apple'}

Remove a random element using pop()

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'}

Remove all the elements

In [67]: s1 = {"apple", "orange",1, "cherry"}


s1.clear()
print("The set becomes:",s1)

The set becomes: set()

Set operations union, intersection, minus

In [68]: s1 = {"apple", "orange","banana", "cherry"}


s2 = {"banana", "orange","mango"}

s3 = s1.union(s2)
# s3 = s1 | s2 # is also same

print("S1:",s1)
print("S2:",s2)
print("S3:",s3)

S1: {'cherry', 'banana', 'apple', 'orange'}


S2: {'mango', 'orange', 'banana'}
S3: {'cherry', 'mango', 'apple', 'banana', 'orange'}

In [69]: s1 = {"apple", "orange","banana", "cherry"}


s2 = {"banana", "orange","mango"}

#s1 = {1, 2,3, 4}


#s2 = {5, 6,7}
print("S1:",s1)
print("S2:",s2)
s3 = s1.intersection(s2)
# s3 = s1 & s2 # is also same
print("Intersection of S1,S2:",s3)
s3 = s1.difference(s2)
# s3 = s1 - s2 # is also same
print("Difference of S1,S2:",s3)

S1: {'cherry', 'banana', 'apple', 'orange'}


S2: {'mango', 'orange', 'banana'}
Intersection of S1,S2: {'banana', 'orange'}
Difference of S1,S2: {'cherry', 'apple'}

Set operations: issubset(<=), issuperset(>=), isdisjoint

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 )

print( "S3 is subset of S2?:",s3.issubset(s2) )


print( "S3 is superset of S2?:",s3.issuperset(s2) )
print( "S2 is superset of S1?:",s2.issuperset(s1) )

print( "S1, S3 disjoint?:",s1.isdisjoint(s3) )


print( "S2, S3 disjoint?:",s2.isdisjoint(s3) )

S1: {'banana', 'orange'}


S2: {'cherry', 'banana', 'apple', 'orange'}
S3: {'2', '1', 'apple', '3'}
S1 is subset of S2?: True
S3 is subset of S2?: False
S3 is superset of S2?: False
S2 is superset of S1?: True
S1, S3 disjoint?: True
S2, S3 disjoint?: False

Set operations: == , != , < , >

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 )

S1 equals to S2?: False


S1 equals to S3?: True
S1 not equals to S2?: True
S1 not equals to S3?: False
S1 is proper subset of S2?: True
S1 is proper superset of S3?: False

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.

In [72]: s1 = {"apple", "orange","banana", "papaya", "cherry"}


print("Length:",len(s1))
print("Min:",min(s1))
print("Max:",max(s1))
print("Sorted :",sorted(s1))

Length: 5
Min: apple
Max: papaya
Sorted : ['apple', 'banana', 'cherry', 'orange', 'papaya']

In [73]: s2 = {"apple", "orange","banana", "cherry"}


print("Sorted Desc:",sorted(s2,reverse=True))

Sorted Desc: ['orange', 'cherry', 'banana', 'apple']

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)

{'name': 'Ravi', 'age': 21, 'branch': 'Chemical'}

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)

Index by int: Text Index by tuple: [123, 45]


Index by int: Text Index by tuple: [123, 45]

Check whether a specific key exists in the dictionary

In [79]: st1 = {
"name": "Ravi",
"age": 21,
"branch": "Chemical"
}

#check a specific key exists


print("Key branch present:",("branch" in st1))
print("Key hostler present:",("hostler" in st1))

Key branch present: True


Key hostler present: False

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.

In [80]: #add new name-value pair


st1 = {
"name": "Ravi",
"age": 21,
"branch": "Chemical"
}
print("Before:",st1)
st1.update({"age":20,"branch": "Petroleum","hostler":"yes"})
print("After:",st1)

Before: {'name': 'Ravi', 'age': 21, 'branch': 'Chemical'}


After: {'name': 'Ravi', 'age': 20, 'branch': 'Petroleum', 'hostler': 'yes'}

Another way to change.


In [81]: st1 = {
"name": "Ravi",
"age": 21,
"branch": "Chemical"
}
print("Before:",st1)
st1["branch"]="Petroleum"

st1["age"]=20
st1["hostler"]="Yes"
print("After:",st1)

Before: {'name': 'Ravi', 'age': 21, 'branch': 'Chemical'}


After: {'name': 'Ravi', 'age': 20, 'branch': 'Petroleum', 'hostler': 'Yes'}

Remvoing a name-value pair

In [82]: #remove a name-value pair


st1 = {
"name": "Ravi",
"age": 21,
"branch": "Chemical"
}
print("Before:",st1)
age = st1.pop("age")
print("Age:",age)

print("After:",st1)

Before: {'name': 'Ravi', 'age': 21, 'branch': 'Chemical'}


Age: 21
After: {'name': 'Ravi', 'branch': 'Chemical'}

Another way to remove.

In [83]: #remove a name-value pair


st1 = {
"name": "Ravi",
"age": 21,
"branch": "Chemical"
}
print("Before:",st1)

del st1["age"] # another way to remove.

print("After:",st1)

Before: {'name': 'Ravi', 'age': 21, 'branch': 'Chemical'}


After: {'name': 'Ravi', 'branch': 'Chemical'}

Invalid Key names gives errors.

In [84]: st1 = {
"name": "Ravi",
"age": 21,
"branch": "Chemical"
}

print(len(st1))
print(st1)

flag = st1.pop("hostler") #raises an error if the key is not present

#del st1["hostler"] #raises an error if the key is not present


na = st1["NAME"] # keys are case sensitive

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())

Keys: dict_keys(['name', 'age', 'branch'])


Values: dict_values(['Ravi', 21, 'Chemical'])
Items: dict_items([('name', 'Ravi'), ('age', 21), ('branch', 'Chemical')])

Nested structures are also possible (e.g tuple as an element inside a list)

In [86]: students = [('Ravi',18, 'Hyd'), ('Kailash',17,'Vizag'), ('John',18,'Goa')]


s=students[1]
name, age, city = s
print(name,city)
print(s)

Kailash Vizag
('Kailash', 17, 'Vizag')

Dictionary Key: name Value: list of contacts

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)

{'email': '[email protected]', 'phone': 9786666555}

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]])

CMR Branches: {'GAJUWAKA', 'MVP'}

Sorted by StoreName:
['CMR', 'SVR', 'SouthIndia']

CMR {'GAJUWAKA', 'MVP'}


SVR {'Madhurawada'}
SouthIndia {'GAJUWAKA', 'Jagadamba'}

In [ ]:

You might also like