SlideShare a Scribd company logo
LIST
TUPLES
SETS
DICTIONARIES
(TELUGU)
2
PYTHON LISTS
3
CREATING LISTS
The list is a datatype available in python, which can be written as list of comma-
separated values between square brackets.
Items or Elements in the list need not be of same data type
Creating list is as simple as putting different comma-separated value between square
brackets.
Example
List1=[“PYTHON”,”DATA STRUCTURES”,”DISCRETE MATHEMATICS”]
List2=[10,20,30,40]
List3=[“PYTHON”,15,”JULY”,2020]
Like Arrays in C, list indices starts at 0 and list can be sliced and concatenated.
4
ACCESSING LISTS
 To access values in lists, use the square brackets for slicing along with index or indices to
obtain value available at that index.
 Example:
List1=[“PYTHON”,”DATA STRUCTURES”,”DISCRETE MATHEMATICS”]
print(List1[0],List1[1],List1[2])
Output:
PYTHON
DATA STRUCTURES
DISCRETE MATHEMATICS
Continued…
5
6
SLICING LISTS
 List slicing is the process of extracting a portion of list from an original list.
 In list slicing programmer was going to cut a list based on what he/she need
(such as where to start, stop and what increment to slice by).
 First argument, index to start slicing.
 Second argument, index to stop slicing.
 Third argument, step/increment to slice by(optional).
Continued…
7
Continued…
8
UPDATING LISTS
(OR)
CHANGING ELEMENTS IN LIST
Python for the data science most in cse.pptx
Python for the data science most in cse.pptx
Python for the data science most in cse.pptx
Python for the data science most in cse.pptx
Python for the data science most in cse.pptx
15
DELETING ELEMENTS OF LISTS
Use del operator to delete an element from a list
del list_name[index]
16
REASSIGNING LISTS
17
MULTI-DIMENSIONAL LISTS
18
Accessing a multidimensional list:
Method:1
#Python program to demonstrate printing of complete multidimensional list
a = [[2, 4, 6, 8, 10], [3, 6, 9, 12, 15], [4, 8, 12, 16, 20]]
print(a)
Output:
[[2, 4, 6, 8, 10], [3, 6, 9, 12, 15], [4, 8, 12, 16, 20]]
Method:2 Accessing with the help of loops
#Python program to demonstrate printing of complete multidimensional list row by row
a = [[2, 4, 6, 8, 10], [3, 6, 9, 12, 15], [4, 8, 12, 16, 20]]
for x in a:
print(x)
Output:
[2, 4, 6, 8, 10]
[3, 6, 9, 12, 15]
[4, 8, 12, 16, 20]
19
Method:3 Accessing array elements using square brackets
#Python program to demonstrate that accessing array elements using square brackets
a = [[2, 4, 6, 8, 10], [3, 6, 9, 12, 15], [4, 8, 12, 16, 20]]
for i in range(len(a)) :
for j in range(len(a[i])) :
print(a[i][j], end=" ")
print()
Output:
2 4 6 8 10
3 6 9 12 15
4 8 12 16 20
20
Methods on Multidimensional lists
1. append(): Adds an element at the end of the list.
Example:
a = [[2, 4, 6, 8, 10], [3, 6, 9, 12, 15], [4, 8, 12, 16, 20]]
a.append([11,12,13,14,15])
print(a)
Output:
[[2, 4, 6, 8, 10], [3, 6, 9, 12, 15], [4, 8, 12, 16, 20], [11, 12, 13, 14, 15]]
2. extend(): Add the elements of a list (or any iterable), to the end of the current list.
Example:
#extending a sublist
a = [[2, 4, 6, 8, 10], [3, 6, 9, 12, 15], [4, 8, 12, 16, 20]]
a[0].extend([11,12,13,14,15])
print(a)
Output:
[[2, 4, 6, 8, 10, 11, 12, 13, 14, 15], [3, 6, 9, 12, 15], [4, 8, 12, 16, 20]]
21
3. reverse(): Reverses the order of the list.
Example:
#reversing a sublist
a = [[2, 4, 6, 8, 10], [3, 6, 9, 12, 15], [4, 8, 12, 16, 20]]
a[0].reverse()
print(a)
Output:
[[10, 8, 6, 4, 2], [3, 6, 9, 12, 15], [4, 8, 12, 16, 20]]
22
CONCATENATION OF LISTS
23
Possible ways to concatenate two lists
Method #1 : Using Naive Method
In this method, we traverse the second list and keep appending elements in the first list, so that first
list would have all the elements in both lists and hence would perform the append.
Example:
#Concatenating 2 Lists
a=[1,2,3,4,5]
b=[11,12,13,14,15,2]
for i in b:
a.append(i)
print("After concatenation"+str(a))
Output:
After concatenation[1, 2, 3, 4, 5, 11, 12, 13, 14, 15, 2]
24
Method #2 : Using + operator
The most conventional method to perform the list concatenation, the use of “+” operator can easily add
the whole of one list behind the other list and hence perform the concatenation.
Example:
#Concatenating 2 Lists
a=[1,2,3,4,5]
b=[11,12,13,14,15,2]
print("After concatenation"+str(a+b))
Output:
After concatenation[1, 2, 3, 4, 5, 11, 12, 13, 14, 15, 2]
25
Method #3 : Using extend()
extend() is the function extended by lists in Python and hence can be used to perform this task. This function
performs the inplace extension of first list.
Example:
#Concatenating 2 Lists
a=[1,2,3,4,5]
b=[11,12,13,14,15,2]
a.extend(b)
print("After concatenation"+str(a))
Output:
After concatenation[1, 2, 3, 4, 5, 11, 12, 13, 14, 15, 2]
26
Method #4 : Using * operator
Using * operator, this method is the new addition to list concatenation and works only in Python 3.6+. Any
no. of lists can be concatenated and returned in a new list using this operator.
Example:
#Concatenating 2 Lists
a=[1,2,3,4,5]
b=[11,12,13,14,15,2]
c=[*a,*b]
print("After concatenation"+str(c))
Output:
After concatenation[1, 2, 3, 4, 5, 11, 12, 13, 14, 15, 2]
27
BASIC OPERATIONS ON LISTS
28
ITERATING ON LISTS
Continued…
29
30
LIST COMPREHENSION
31
Continued…
32
33
LIST BUILT-IN FUNCTIONS / METHODS
Continued…
1. append()
2. extend()
3. insert()
4. remove()
5. pop()
6. Slice
7. Reverse()
8. len()
9. min() & max()
10.count()
11. index()
12.sort()
13. clear()
34
1. append()
The append() method is used to add elements at the end of the list. This method can only add a single
element at a time. To add multiple elements, the append() method can be used inside a loop.
Example: myList = [1, 2, 3, ‘EduCBA’, ‘makes learning fun!’]
myList.append(4)
myList.append(5)
myList.append(6)
for i in range(7, 9):
myList.append(i)
print(myList)
Output:
[1, 2, 3, 'EduCBA', 'makes learning fun!', 4, 5, 6, 7, 8]
35
2. extend()
The extend() method is used to add more than one element at the end of the list. Although it can add more than
one element unlike append(), it adds them at the end of the list like append().
Example:
myList.extend([4,5,6])
for i in range(7, 9):
myList.append(i)
print(myList)
Output: [1, 2, 3, 'EduCBA', 'makes learning fun!', 4, 5, 6, 7, 8]
36
3. insert()
The insert() method can add an element at a given position in the list. Thus, unlike append(), it can add
elements at any position but like append(), it can add only one element at a time. This method takes two
arguments. The first argument specifies the position and the second argument specifies the element to be
inserted.
Example:
myList = [1, 2, 3, "EduCBA", "makes learning fun!"]
myList.insert(3, 4)
myList.insert(4, 5)
myList.insert(5, 6)
print(myList)
Output: [1, 2, 3, 4, 5, 6, 'EduCBA', 'makes learning fun!']
37
4. remove()
The remove() method is used to remove an element from the list. In the case of multiple occurrences of the
same element, only the first occurrence is removed.
Example:
myList = [1, 2, 3, "EduCBA", "makes learning fun!"]
myList.remove('makes learning fun!')
myList.insert(4, 'makes')
print(myList)
Output:
[1, 2, 3, 'EduCBA', 'makes']
38
5. pop()
The method pop() can remove an element from any position in the list. The parameter supplied to this
method is the index of the element to be removed.
Example:
myList = [1, 2, 3, "EduCBA", "makes learning fun!"]
myList.pop(4)
myList.insert(4, 'makes')
myList.insert(5, 'learning')
myList.insert(6, 'so much fun!')
print(myList)
Output:
[1, 2, 3, 'EduCBA', 'makes', 'learning', 'so much fun!']
39
6. Slice
The Slice operation is used to print a section of the list. The Slice operation returns a specific range
of elements. It does not modify the original list.
Example:
myList = [1, 2, 3, "EduCBA", "makes learning fun!"]
print(myList[:4]) # prints from beginning to end index
print(myList[2:]) # prints from start index to end of list
print(myList[2:4]) # prints from start index to end index
print(myList[:]) # prints from beginning to end of list
Output:
[1, 2, 3, 'EduCBA']
[3, 'EduCBA', 'makes learning fun!']
[3, 'EduCBA']
[1, 2, 3, 'EduCBA', 'makes learning fun!']
40
7. Reverse()
The reverse() operation is used to reverse the elements of the list. This method modifies the original list.
To reverse a list without modifying the original one, we use the slice operation with negative indices.
Specifying negative indices iterates the list from the rear end to the front end of the list.
Example:
myList = [1, 2, 3, "EduCBA", "makes learning fun!"]
print(myList[::-1]) # does not modify the original list
myList.reverse() # modifies the original list
print(myList)
Output:
['makes learning fun!', 'EduCBA', 3, 2, 1]
['makes learning fun!', 'EduCBA', 3, 2, 1]
41
8. len()
The len() method returns the length of the list, i.e. the number of elements in the list.
Example:
myList = [1, 2, 3, "EduCBA", "makes learning fun!"]
print(len(myList))
Output:
5
9. min() & max()
The min() method returns the minimum value in the list. The max() method returns the maximum value
in the list. Both the methods accept only homogeneous lists, i.e. list having elements of similar type.
Example:
myList = [1, 2, 3]
print(min(myList))
42
10. count()
The function count() returns the number of occurrences of a given element in the list.
Example:
myList = [1, 2, 3]
print(myList.count(3))
11. index()
The index() method returns the position of the first occurrence of the given element. It takes two
optional parameters – the begin index and the end index. These parameters define the start and end
position of the search area on the list. When supplied, the element is searched only in the sub-list bound
by the begin and end indices. When not supplied, the element is searched in the whole list.
Example:
myList = [1, 2, 3,"EduCBA"]
print(myList.index('EduCBA')) # searches in the whole list
print(myList.index('EduCBA', 0, 2)) # searches from 0th to 2nd position
43
12. sort()
The sort method sorts the list in ascending order. This operation can only be performed on homogeneous
lists, i.e. lists having elements of similar type.
Example:
yourList = [4, 2, 6, 5, 0, 1]
yourList.sort()
print(yourList)
13. clear()
This function erases all the elements from the list and empties it.
Example:
yourList = [4, 2, 6, 5, 0, 1]
yourList.clear()
print(yourList)
TUPLES
Python for the data science most in cse.pptx
Python for the data science most in cse.pptx
Python for the data science most in cse.pptx
# Different types of tuples
# Empty tuple
my_tuple = ()
print(my_tuple)
# Tuple having integers
my_tuple = (1, 2, 3)
print(my_tuple)
# tuple with mixed datatypes
my_tuple = (1, "Hello", 3.4)
print(my_tuple)
# nested tuple
my_tuple = ("mouse", [8, 4, 6], (1, 2, 3))
print(my_tuple)
()
(1, 2, 3)
(1, 'Hello', 3.4)
('mouse', [8, 4, 6], (1, 2, 3))
A tuple can also be created without using parentheses.
This is known as tuple packing.
my_tuple = 3, 4.6, "dog"
print(my_tuple)
# tuple unpacking is also possible
a, b, c = my_tuple
print(a) # 3
print(b) # 4.6
print(c) # dog
Output
(3, 4.6, 'dog’)
3
4.6
dog
cess Tuple Elements
ere are various ways in which we can access the elements of a tuple.
ndexing
can use the index operator [] to access an item in a tuple,
ere the index starts from 0.
a tuple having 6 elements will have indices from 0 to 5.
ing to access an index outside
he tuple index range(6,7,... in this example)
raise an IndexError.
e index must be an integer,
we cannot use float or other types.
is will result in TypeError.
# Accessing tuple elements using indexing
my_tuple = ('p','e','r','m','i','t')
print(my_tuple[0]) # 'p'
print(my_tuple[5]) # 't'
# IndexError: list index out of range
# print(my_tuple[6])
# Index must be an integer
# TypeError: list indices must be integers, not float
# my_tuple[2.0]
# nested tuple
n_tuple = ("mouse", [8, 4, 6], (1, 2, 3))
# nested index
print(n_tuple[0][3]) # 's'
print(n_tuple[1][1]) # 4
Output
P
t
S
4
2. Negative Indexing
Python allows negative indexing for its sequences.
The index of -1 refers to the last item, -2 to the second
last item and so on.
# Negative indexing for accessing tuple elements
my_tuple = ('p', 'e', 'r', 'm', 'i', 't')
# Output: 't'
print(my_tuple[-1])
# Output: 'p'
print(my_tuple[-6])
3. Slicing
We can access a range of items in a tuple by using the slicing operator colon :
# Accessing tuple elements using slicing
my_tuple = ('p','r','o','g','r','a','m','i','z')
# elements 2nd to 4th
# Output: ('r', 'o', 'g')
print(my_tuple[1:4])
# elements beginning to 2nd
# Output: ('p', 'r')
print(my_tuple[:-7])
# elements 8th to end
# Output: ('i', 'z')
print(my_tuple[7:])
# elements beginning to end
# Output: ('p', 'r', 'o', 'g', 'r', 'a', 'm', 'i', 'z')
print(my_tuple[:])
Output
('r', 'o', 'g’)
('p', 'r’)
('i', 'z’)
('p', 'r', 'o', 'g', 'r', 'a', 'm', 'i', 'z')
Python for the data science most in cse.pptx
Python for the data science most in cse.pptx
Python for the data science most in cse.pptx
Python for the data science most in cse.pptx
Changing a Tuple
Unlike lists, tuples are immutable.
This means that elements of a tuple cannot be
changed once they have been assigned. But, if the
element is itself a mutable data type like a list, its
nested items can be changed.
We can also assign a tuple to different values
(reassignment).
# Changing tuple values
my_tuple = (4, 2, 3, [6, 5])
# TypeError: 'tuple' object does not support item assignment
# my_tuple[1] = 9
# However, item of mutable element can be changed
my_tuple[3][0] = 9 # Output: (4, 2, 3, [9, 5])
print(my_tuple)
# Tuples can be reassigned
my_tuple = ('p', 'r', 'o', 'g', 'r', 'a', 'm', 'i', 'z')
# Output: ('p', 'r', 'o', 'g', 'r', 'a', 'm', 'i', 'z')
print(my_tuple)
Output
(4, 2, 3, [9, 5])
('p', 'r', 'o', 'g', 'r', 'a', 'm', 'i', 'z')
Python for the data science most in cse.pptx
Other Tuple Operations
1. Tuple Membership Test
We can test if an item exists in a tuple or not, using the keyword in.
# Membership test in tuple
my_tuple = ('a', 'p', 'p', 'l', 'e',)
# In operation
print('a' in my_tuple)
print('b' in my_tuple)
# Not in operation
print('g' not in my_tuple)
Output
True
False
True
Python for the data science most in cse.pptx
#!/usr/bin/python
tuple1, tuple2 = (123, 'xyz', 'zara'), (456, 'abc’)
print "First tuple length : ", len(tuple1)
print "Second tuple length : ", len(tuple2)
#!/usr/bin/python3tuple1, tuple2 = ('maths', 'che', 'phy', 'bio'),
(456, 700, 200)
print ("Max value element : ", max(tuple1))
print ("Max value element : ", max(tuple2))
#!/usr/bin/python3tuple1, tuple2 = ('maths', 'che', 'phy', 'bio'),
(456, 700, 200)
print ("Max value element : ", min(tuple1))
print ("Max value element : ", min(tuple2))
# when an iterable(e.g., list) is passed
list1= [ 1, 2, 3, 4 ]
tuple2 = tuple(list1)
print(tuple2)
Python for the data science most in cse.pptx
# initializing list
test_list = [(4, 6), (1, 2), (9, 2), (2, 1), (5, 7), (6, 4), (9, 2)]
# printing original list
print("The original list is : " + str(test_list))
# using map() to get all sorted
# set removes duplicates
res = list({*map(tuple, map(sorted, test_list))})
# printing result
print("Tuples after removal : " + str(res))
Python Program to Remove duplicate tuples irrespective of
order
runfile('D:/python examples/untitled6.py', wdir='D:/python
examples')
The original list is : [(4, 6), (1, 2), (9, 2), (2, 1), (5, 7), (6, 4), (9, 2)]
Tuples after removal : [(2, 9), (1, 2), (4, 6), (5, 7)]
# initializing lists
test_list = [(3, -1), (-4, -3), (1, 3), (-2, 5), (-4, 2), (-9, -3)]
# printing original list
print("The original list is : " + str(test_list))
res = []
for sub in test_list:
# 2nd element converted to negative magnitude
res.append((abs(sub[0]), -abs(sub[1])))
# printing result
print("Updated Tuple list : " + str(res))
Change the signs of elements of tuples in a list
Output:
The original list is : [(3, -1), (-4, -3), (1, 3), (-2, 5), (-4, 2), (-9, -3)]
Updated Tuple list : [(3, -1), (4, -3), (1, -3), (2, -5), (4, -2), (9, -3)]
Python program to Sort a List of Tuples in Increasing Order by the Last Element in
Each Tuple
e task is to write a Python Program to sort a list of tuples in increasing order by the last element in each tuple.
put: [(1, 3), (3, 2), (2, 1)]
tput: [(2, 1), (3, 2), (1, 3)]
planation: sort tuple based on the last digit of each tuple.
Methods #1: Using sorted().
Sorted() method sorts a list and always returns a list with the elements in a sorted manner, without modifying the
original sequence.
Approach:
•Take a list of tuples from the user.
•Define a function that returns the last element of each tuple in the list of tuples.
•Define another function with the previous function as the key and sort the list.
•Print the sorted list.
•Python3
def last(n):
return n[-1]
def sort(tuples):
return sorted(tuples, key=last)
a=[(1, 3), (3, 2), (2, 1)]
print("Sorted:")
print(sort(a))
Python for the data science most in cse.pptx
sets
SETS in Python
A set is an unordered collection of items. Every set element is unique (no duplicates) and
must be immutable (cannot be changed).
However, a set itself is mutable. We can add or remove items from it.
Sets can also be used to perform mathematical set operations like union, intersection,
symmetric difference, etc.
reating Python Sets
set is created by placing all the items (elements) inside curly braces {}, separated by comma,
r by using the built-in set() function.
can have any number of items and they may be of different types (integer, float, tuple, string etc.).
ut a set cannot have mutable elements like lists, sets or dictionaries as its elements.
# Different types of sets in Python
# set of integers
my_set = {1, 2, 3}
print(my_set)
# set of mixed datatypes
my_set = {1.0, "Hello", (1, 2, 3)}
print(my_set)
Output
{1, 2, 3} {1.0, (1, 2, 3), 'Hello'}
# set cannot have duplicates
# Output: {1, 2, 3, 4}
my_set = {1, 2, 3, 4, 3, 2}
print(my_set)
# we can make set from a list
# Output: {1, 2, 3}
my_set = set([1, 2, 3, 2])
print(my_set)
# set cannot have mutable items
# here [3, 4] is a mutable list
# this will cause an error.
my_set = {1, 2, [3, 4]} {1, 2, 3, 4}
{1, 2, 3}
Traceback (most recent call last):
File "<string>", line 15, in <module>
my_set = {1, 2, [3, 4]}
TypeError: unhashable type: 'list'
ating an empty set is a bit tricky.
pty curly braces {} will make an empty dictionary in Python.
make a set without any elements, we use the set() function without any argument.
# Distinguish set and dictionary while creating empty set
# initialize a with {}
a = {}
# check data type of a
print(type(a))
# initialize a with set()
a = set()
# check data type of a
print(type(a))
Output
<class 'dict’>
<class 'set'>
Modifying a set in Python
Sets are mutable. However, since they are unordered, indexing has no meaning.
We cannot access or change an element of a set using indexing or slicing.
et data type does not support it.
We can add a single element using the add() method, and multiple elements
using the update() method.
The update() method can take tuples, lists, strings or other sets as its argument.
In all cases, duplicates are avoided.
# initialize my_set
my_set = {1, 3}
print(my_set)
# my_set[0]
# if you uncomment the above line
# you will get an error
# TypeError: 'set' object does not support indexing
# add an element
# Output: {1, 2, 3}
my_set.add(2)
print(my_set)
# add multiple elements
# Output: {1, 2, 3, 4}
my_set.update([2, 3, 4])
print(my_set)
# add list and set
# Output: {1, 2, 3, 4, 5, 6, 8}
my_set.update([4, 5], {1, 6, 8})
print(my_set)
Output
{1, 3}
{1, 2, 3}
{1, 2, 3, 4}
{1, 2, 3, 4, 5, 6, 8}
Removing elements from a set
A particular item can be removed from a set using the methods
discard() and remove().
The only difference between the two is that the discard() function leaves a set
unchanged if the element is not present in the set.
On the other hand, the remove() function will raise an error in
such a condition (if element is not present in the set).
The following example will illustrate this.
# Difference between discard() and remove()
# initialize my_set
my_set = {1, 3, 4, 5, 6}
print(my_set)
# discard an element
# Output: {1, 3, 5, 6}
my_set.discard(4)
print(my_set)
# remove an element
# Output: {1, 3, 5}
my_set.remove(6)
print(my_set)
# discard an element
# not present in my_set
# Output: {1, 3, 5}
my_set.discard(2)
print(my_set)
# remove an element
# not present in my_set
# you will get an error.
# Output: KeyError
my_set.remove(2)
Output
{1, 3, 4, 5, 6}
{1, 3, 5, 6}
{1, 3, 5}
{1, 3, 5}
Traceback (most recent call last):
File "<string>", line 28, in <module>
KeyError: 2
milarly, we can remove and return an item using the pop() method.
nce set is an unordered data type, there is no way of determining which item will be popped.
is completely arbitrary.
e can also remove all the items from a set using the clear() method.
# initialize my_set
# Output: set of unique elements
my_set = set("HelloWorld")
print(my_set)
# pop an element
# Output: random element
print(my_set.pop())
# pop another element
my_set.pop()
print(my_set)
# clear my_set
# Output: set()
my_set.clear()
print(my_set)
print(my_set)
{'H', 'l', 'r', 'W', 'o', 'd', 'e’}
H
{'r', 'W', 'o', 'd', 'e’}
set()
Python Set Operations
Sets can be used to carry out mathematical set operations like union,
intersection, difference and symmetric difference. We can do this with
operators or methods.
Let us consider the following two sets for the following operations.
>>> A = {1, 2, 3, 4,
5}
>>> B = {4, 5, 6, 7,
8}
Set Union
Set Union in
Python
Union of and
A B is a set of all elements from both
sets.
Union is performed using | operator. Same can be accomplished using
th
e
union() method.
# Set union method
# initialize A and B A = {1, 2, 3, 4, 5}
B = {4, 5, 6, 7, 8}
# use | operator
# Output: {1, 2, 3, 4, 5, 6, 7, 8}
print(A | B)
Output
{1, 2, 3, 4, 5, 6, 7, 8}
Try the following examples on Python shell.
# use union function
>>> A.union(B)
{1, 2, 3, 4, 5, 6, 7, 8}
# use union function on B
>>> B.union(A)
{1, 2, 3, 4, 5, 6, 7, 8}
Set Intersection
Set Intersection in
Python
Intersection of
sets.
A and is a set of elements that are common in both
the
B
Intersection is performed using & operator. Same can be
accomplished
using theintersection() method.
# Intersection of sets
# initialize A and B A = {1, 2, 3, 4, 5}
B = {4, 5, 6, 7, 8}
# use intersection function on A
>>> A.intersection(B)
{4, 5}
# use intersection function on B
>>> B.intersection(A)
{4, 5}
Set Difference
Set Difference in
Python
Difference of the set B from set A(A - B) is a set of elements that are
only
in but not in B.
Similarly,
A B - is a set of elements
in
A B but not in A.
# use & operator
# Output: {4, 5} print(A & B)
Output
{4, 5}
Try the following examples on Python shell.
Difference is performed using
the difference() method.
- operator. Same can be accomplished
using
# Difference of two sets
# initialize A and B A = {1, 2, 3, 4, 5}
B = {4, 5, 6, 7, 8}
# use - operator on A
# Output: {1, 2, 3} print(A - B)
Output
{1, 2, 3}
Try the following examples on Python shell.
# use difference function on A
>>> A.difference(B)
{1, 2, 3}
# use - operator on B
>>> B - A
{8, 6, 7}
# use difference function on B
>>> B.difference(A)
{8, 6, 7}
Set Symmetric Difference
Set Symmetric
Difference in Python
Symmetric Difference of A and B is a set of elements
in
A and but not in
B
both (excluding the intersection).
Symmetric difference is performed using operator. Same can
be
^
accomplished using the method symmetric_difference().
# Symmetric difference of two sets
# initialize A and B A = {1, 2, 3, 4, 5}
B = {4, 5, 6, 7, 8}
# use ^ operator
# Output: {1, 2, 3, 6, 7, 8}
print(A ^ B)
Output
{1, 2, 3, 6, 7, 8}
Try the following examples on Python shell.
# use symmetric_difference function on A
>>> A.symmetric_difference(B)
{1, 2, 3, 6, 7, 8}
# use symmetric_difference function on B
>>> B.symmetric_difference(A)
{1, 2, 3, 6, 7, 8}
Other Python Set Methods
There are many set methods, some of which we have already used above.
Here is a list of all the methods that are available with the set objects:
Method
Description
add() Adds an element to the set
clear() Removes all elements from the
set
copy() Returns a copy of the set
difference() Returns the difference of two or more sets as a new
set
difference_update() Removes all elements of another set from this
set
discard()
Removes an element from the set if it is a member. (Do
nothing if the element is not in set)
intersection() Returns the intersection of two sets as a new
set
intersection_update() Updates the set with the intersection of itself and
another
isdisjoint(
)
Returns if two sets have a null
intersection
Tru
e
issubset() Returns if another set contains this
set
Tru
e
issuperset() Returns if this set contains another
set
Tru
e
pop()
Removes and returns an arbitrary set element.
Raises
KeyError if the set is
empty
remove()
Removes an element from the set. If the element is not
a
member, raises a
KeyError
symmetric_difference() Returns the symmetric difference of two sets as a new
set
symmetric_difference_update(
)
Updates a set with the symmetric difference of itself
and
another
union() Returns the union of sets in a new
set
update() Updates the set with the union of itself and
others
Other Set Operations
Set Membership Test
We can test if an item exists in a set or not, using the in
keyword.
Iterating Through a Set
# in keyword in a set
# initialize my_set my_set = set("apple")
# check if 'a' is present
# Output: True print('a' in my_set)
# check if 'p' is present
# Output: False print('p' not in my_set)
Output
True False
We can iterate through each item in a set using a for loop.
>>> for letter in set("apple"):
..
.
..
.
a p
e l
print(lette
r)
Built-in Functions with Set
Built-in functions
like all(), any(), enumerate(), len(), max(), min(),
sorted(),
sum(
)
etc. are
commonly used with sets to perform different
tasks.
Function Description
all() Returns if all elements of the set are true (or if the set is
empty).
Tru
e
any() Returns if any element of the set is true. If the set is empty, returns
False.
Tru
e
enumerate()
Returns an enumerate object. It contains the index and value for all the items of
the set as a pair.
len() Returns the length (the number of items) in the
set.
max() Returns the largest item in the
set.
min() Returns the smallest item in the
set.
sorted() Returns a new sorted list from elements in the set(does not sort the set
itself).
sum() Returns the sum of all elements in the
set.
Python Frozenset
Frozenset is a new class that has the characteristics of a set, but its elements
cannot be changed once assigned. While tuples are immutable lists,
frozensets are immutable sets.
Sets being mutable are unhashable, so they can't be used as dictionary keys.
On the other hand, frozensets are hash able and can be used as keys to a
dictionary.
Frozensets can be created using the frozenset() function.
This data type supports methods
like copy(), difference(), intersection(), isdisjoint(),
issubset(),
issuperset
(
), symmetric_difference
()
and union(). Being immutable, it does not
have
methods that add or remove elements.
# Frozensets
# initialize A and B
A = frozenset([1, 2, 3, 4])
B = frozenset([3, 4, 5, 6])
Try these examples on Python shell.
>>> A.isdisjoint(B) False
>>> A.difference(B) frozenset({1, 2})
>>> A | B
frozenset({1, 2, 3, 4, 5, 6})
>>> A.add(3)
...
AttributeError: 'frozenset' object has no attribute 'add'
Python for the data science most in cse.pptx
Python for the data science most in cse.pptx
Python for the data science most in cse.pptx
Python for the data science most in cse.pptx
DICTIONARIES
Python for the data science most in cse.pptx
Python for the data science most in cse.pptx
Python for the data science most in cse.pptx
Python for the data science most in cse.pptx
Python for the data science most in cse.pptx
Python for the data science most in cse.pptx
Python for the data science most in cse.pptx
Python for the data science most in cse.pptx
Python for the data science most in cse.pptx
Python for the data science most in cse.pptx
Python for the data science most in cse.pptx

More Related Content

PPTX
PYTHON-PROGRAMMING-UNIT-III.pptx kghbg kfhjf jruufg jtuuf
PDF
Python List
DOCX
List Data Structure.docx
PPT
UNIT 4 PY.ppt - DATA STRUCTURE IN PYTHON
PPTX
powerpoint 2-13.pptx
PPTX
Unit 4 python -list methods
PYTHON-PROGRAMMING-UNIT-III.pptx kghbg kfhjf jruufg jtuuf
Python List
List Data Structure.docx
UNIT 4 PY.ppt - DATA STRUCTURE IN PYTHON
powerpoint 2-13.pptx
Unit 4 python -list methods

Similar to Python for the data science most in cse.pptx (20)

PPTX
Unit 4.pptx python list tuples dictionary
PDF
Unit 1-Part-4-Lists, tuples and dictionaries.pdf
PPTX
python lists with examples and explanation python lists with examples and ex...
PDF
List,tuple,dictionary
PPTX
List in Python
PPTX
Module-2.pptx
PPTX
Python list
PPTX
Chapter 15 Lists
PPTX
listtupledictionary-2001okdhfuihcasbdjj02082611.pptx
PDF
python_avw - Unit-03.pdf
PDF
Python lists &amp; sets
PPTX
list in python and traversal of list.pptx
PPTX
list and control statement.pptx
PPTX
Pythonlearn-08-Lists (1).pptxaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa...
PPTX
updated_list.pptx
PDF
Data type list_methods_in_python
PPTX
institute of techonolgy and education tr
PPTX
Python Collection datatypes
PPTX
Lists.pptx
Unit 4.pptx python list tuples dictionary
Unit 1-Part-4-Lists, tuples and dictionaries.pdf
python lists with examples and explanation python lists with examples and ex...
List,tuple,dictionary
List in Python
Module-2.pptx
Python list
Chapter 15 Lists
listtupledictionary-2001okdhfuihcasbdjj02082611.pptx
python_avw - Unit-03.pdf
Python lists &amp; sets
list in python and traversal of list.pptx
list and control statement.pptx
Pythonlearn-08-Lists (1).pptxaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa...
updated_list.pptx
Data type list_methods_in_python
institute of techonolgy and education tr
Python Collection datatypes
Lists.pptx
Ad

More from Rajasekhar364622 (20)

PPTX
introduction to database system concepts 2
PPTX
introduction to database system concepts
PPTX
OS Introduction Operating systems Processes and concepts
PPT
Operating systems Processes and concepts
PPTX
Prompt_Engineering_ chat Presentation.pptx
PPTX
Revolutionizing ChatGPT_Presentation.pptx
PPTX
digital computer present situations.pptx
PPTX
Python variables in the computer science.pptx
PPT
Unit 2 chapter notes for the student1-1.ppt
PPTX
MACHINE LEARNING TECHNOLOGY for the topic
PPTX
Touchscreen Technology used now -1.pptx
PPTX
Presentation on present trending technologys
PPT
python and web for data science prfrograminh
PPT
functions modules and exceptions handlings.ppt
PPTX
Machine learning how are things going on
PPT
Using Tree algorithms on machine learning
PPTX
DBMS-material for b.tech students to learn
PPT
unit5-academic writing human intraction.ppt
PPTX
Advantages and disadvantages of ML .PPTX
PPTX
BLOCK CHAIN technology for the students.
introduction to database system concepts 2
introduction to database system concepts
OS Introduction Operating systems Processes and concepts
Operating systems Processes and concepts
Prompt_Engineering_ chat Presentation.pptx
Revolutionizing ChatGPT_Presentation.pptx
digital computer present situations.pptx
Python variables in the computer science.pptx
Unit 2 chapter notes for the student1-1.ppt
MACHINE LEARNING TECHNOLOGY for the topic
Touchscreen Technology used now -1.pptx
Presentation on present trending technologys
python and web for data science prfrograminh
functions modules and exceptions handlings.ppt
Machine learning how are things going on
Using Tree algorithms on machine learning
DBMS-material for b.tech students to learn
unit5-academic writing human intraction.ppt
Advantages and disadvantages of ML .PPTX
BLOCK CHAIN technology for the students.
Ad

Recently uploaded (20)

PPTX
Recipes for Real Time Voice AI WebRTC, SLMs and Open Source Software.pptx
PDF
Operating System & Kernel Study Guide-1 - converted.pdf
PPTX
Engineering Ethics, Safety and Environment [Autosaved] (1).pptx
PPTX
CARTOGRAPHY AND GEOINFORMATION VISUALIZATION chapter1 NPTE (2).pptx
PPT
CRASH COURSE IN ALTERNATIVE PLUMBING CLASS
PPTX
Geodesy 1.pptx...............................................
PPTX
Lecture Notes Electrical Wiring System Components
PDF
BMEC211 - INTRODUCTION TO MECHATRONICS-1.pdf
PDF
SM_6th-Sem__Cse_Internet-of-Things.pdf IOT
DOCX
573137875-Attendance-Management-System-original
PDF
Mohammad Mahdi Farshadian CV - Prospective PhD Student 2026
PPTX
MCN 401 KTU-2019-PPE KITS-MODULE 2.pptx
PDF
Embodied AI: Ushering in the Next Era of Intelligent Systems
PPTX
OOP with Java - Java Introduction (Basics)
PPTX
KTU 2019 -S7-MCN 401 MODULE 2-VINAY.pptx
PDF
composite construction of structures.pdf
PDF
Model Code of Practice - Construction Work - 21102022 .pdf
PDF
July 2025 - Top 10 Read Articles in International Journal of Software Enginee...
PDF
TFEC-4-2020-Design-Guide-for-Timber-Roof-Trusses.pdf
PPTX
IOT PPTs Week 10 Lecture Material.pptx of NPTEL Smart Cities contd
Recipes for Real Time Voice AI WebRTC, SLMs and Open Source Software.pptx
Operating System & Kernel Study Guide-1 - converted.pdf
Engineering Ethics, Safety and Environment [Autosaved] (1).pptx
CARTOGRAPHY AND GEOINFORMATION VISUALIZATION chapter1 NPTE (2).pptx
CRASH COURSE IN ALTERNATIVE PLUMBING CLASS
Geodesy 1.pptx...............................................
Lecture Notes Electrical Wiring System Components
BMEC211 - INTRODUCTION TO MECHATRONICS-1.pdf
SM_6th-Sem__Cse_Internet-of-Things.pdf IOT
573137875-Attendance-Management-System-original
Mohammad Mahdi Farshadian CV - Prospective PhD Student 2026
MCN 401 KTU-2019-PPE KITS-MODULE 2.pptx
Embodied AI: Ushering in the Next Era of Intelligent Systems
OOP with Java - Java Introduction (Basics)
KTU 2019 -S7-MCN 401 MODULE 2-VINAY.pptx
composite construction of structures.pdf
Model Code of Practice - Construction Work - 21102022 .pdf
July 2025 - Top 10 Read Articles in International Journal of Software Enginee...
TFEC-4-2020-Design-Guide-for-Timber-Roof-Trusses.pdf
IOT PPTs Week 10 Lecture Material.pptx of NPTEL Smart Cities contd

Python for the data science most in cse.pptx

  • 3. 3 CREATING LISTS The list is a datatype available in python, which can be written as list of comma- separated values between square brackets. Items or Elements in the list need not be of same data type Creating list is as simple as putting different comma-separated value between square brackets. Example List1=[“PYTHON”,”DATA STRUCTURES”,”DISCRETE MATHEMATICS”] List2=[10,20,30,40] List3=[“PYTHON”,15,”JULY”,2020] Like Arrays in C, list indices starts at 0 and list can be sliced and concatenated.
  • 4. 4 ACCESSING LISTS  To access values in lists, use the square brackets for slicing along with index or indices to obtain value available at that index.  Example: List1=[“PYTHON”,”DATA STRUCTURES”,”DISCRETE MATHEMATICS”] print(List1[0],List1[1],List1[2]) Output: PYTHON DATA STRUCTURES DISCRETE MATHEMATICS Continued…
  • 5. 5
  • 6. 6 SLICING LISTS  List slicing is the process of extracting a portion of list from an original list.  In list slicing programmer was going to cut a list based on what he/she need (such as where to start, stop and what increment to slice by).  First argument, index to start slicing.  Second argument, index to stop slicing.  Third argument, step/increment to slice by(optional). Continued…
  • 8. 8
  • 15. 15 DELETING ELEMENTS OF LISTS Use del operator to delete an element from a list del list_name[index]
  • 18. 18 Accessing a multidimensional list: Method:1 #Python program to demonstrate printing of complete multidimensional list a = [[2, 4, 6, 8, 10], [3, 6, 9, 12, 15], [4, 8, 12, 16, 20]] print(a) Output: [[2, 4, 6, 8, 10], [3, 6, 9, 12, 15], [4, 8, 12, 16, 20]] Method:2 Accessing with the help of loops #Python program to demonstrate printing of complete multidimensional list row by row a = [[2, 4, 6, 8, 10], [3, 6, 9, 12, 15], [4, 8, 12, 16, 20]] for x in a: print(x) Output: [2, 4, 6, 8, 10] [3, 6, 9, 12, 15] [4, 8, 12, 16, 20]
  • 19. 19 Method:3 Accessing array elements using square brackets #Python program to demonstrate that accessing array elements using square brackets a = [[2, 4, 6, 8, 10], [3, 6, 9, 12, 15], [4, 8, 12, 16, 20]] for i in range(len(a)) : for j in range(len(a[i])) : print(a[i][j], end=" ") print() Output: 2 4 6 8 10 3 6 9 12 15 4 8 12 16 20
  • 20. 20 Methods on Multidimensional lists 1. append(): Adds an element at the end of the list. Example: a = [[2, 4, 6, 8, 10], [3, 6, 9, 12, 15], [4, 8, 12, 16, 20]] a.append([11,12,13,14,15]) print(a) Output: [[2, 4, 6, 8, 10], [3, 6, 9, 12, 15], [4, 8, 12, 16, 20], [11, 12, 13, 14, 15]] 2. extend(): Add the elements of a list (or any iterable), to the end of the current list. Example: #extending a sublist a = [[2, 4, 6, 8, 10], [3, 6, 9, 12, 15], [4, 8, 12, 16, 20]] a[0].extend([11,12,13,14,15]) print(a) Output: [[2, 4, 6, 8, 10, 11, 12, 13, 14, 15], [3, 6, 9, 12, 15], [4, 8, 12, 16, 20]]
  • 21. 21 3. reverse(): Reverses the order of the list. Example: #reversing a sublist a = [[2, 4, 6, 8, 10], [3, 6, 9, 12, 15], [4, 8, 12, 16, 20]] a[0].reverse() print(a) Output: [[10, 8, 6, 4, 2], [3, 6, 9, 12, 15], [4, 8, 12, 16, 20]]
  • 23. 23 Possible ways to concatenate two lists Method #1 : Using Naive Method In this method, we traverse the second list and keep appending elements in the first list, so that first list would have all the elements in both lists and hence would perform the append. Example: #Concatenating 2 Lists a=[1,2,3,4,5] b=[11,12,13,14,15,2] for i in b: a.append(i) print("After concatenation"+str(a)) Output: After concatenation[1, 2, 3, 4, 5, 11, 12, 13, 14, 15, 2]
  • 24. 24 Method #2 : Using + operator The most conventional method to perform the list concatenation, the use of “+” operator can easily add the whole of one list behind the other list and hence perform the concatenation. Example: #Concatenating 2 Lists a=[1,2,3,4,5] b=[11,12,13,14,15,2] print("After concatenation"+str(a+b)) Output: After concatenation[1, 2, 3, 4, 5, 11, 12, 13, 14, 15, 2]
  • 25. 25 Method #3 : Using extend() extend() is the function extended by lists in Python and hence can be used to perform this task. This function performs the inplace extension of first list. Example: #Concatenating 2 Lists a=[1,2,3,4,5] b=[11,12,13,14,15,2] a.extend(b) print("After concatenation"+str(a)) Output: After concatenation[1, 2, 3, 4, 5, 11, 12, 13, 14, 15, 2]
  • 26. 26 Method #4 : Using * operator Using * operator, this method is the new addition to list concatenation and works only in Python 3.6+. Any no. of lists can be concatenated and returned in a new list using this operator. Example: #Concatenating 2 Lists a=[1,2,3,4,5] b=[11,12,13,14,15,2] c=[*a,*b] print("After concatenation"+str(c)) Output: After concatenation[1, 2, 3, 4, 5, 11, 12, 13, 14, 15, 2]
  • 29. 29
  • 32. 32
  • 33. 33 LIST BUILT-IN FUNCTIONS / METHODS Continued… 1. append() 2. extend() 3. insert() 4. remove() 5. pop() 6. Slice 7. Reverse() 8. len() 9. min() & max() 10.count() 11. index() 12.sort() 13. clear()
  • 34. 34 1. append() The append() method is used to add elements at the end of the list. This method can only add a single element at a time. To add multiple elements, the append() method can be used inside a loop. Example: myList = [1, 2, 3, ‘EduCBA’, ‘makes learning fun!’] myList.append(4) myList.append(5) myList.append(6) for i in range(7, 9): myList.append(i) print(myList) Output: [1, 2, 3, 'EduCBA', 'makes learning fun!', 4, 5, 6, 7, 8]
  • 35. 35 2. extend() The extend() method is used to add more than one element at the end of the list. Although it can add more than one element unlike append(), it adds them at the end of the list like append(). Example: myList.extend([4,5,6]) for i in range(7, 9): myList.append(i) print(myList) Output: [1, 2, 3, 'EduCBA', 'makes learning fun!', 4, 5, 6, 7, 8]
  • 36. 36 3. insert() The insert() method can add an element at a given position in the list. Thus, unlike append(), it can add elements at any position but like append(), it can add only one element at a time. This method takes two arguments. The first argument specifies the position and the second argument specifies the element to be inserted. Example: myList = [1, 2, 3, "EduCBA", "makes learning fun!"] myList.insert(3, 4) myList.insert(4, 5) myList.insert(5, 6) print(myList) Output: [1, 2, 3, 4, 5, 6, 'EduCBA', 'makes learning fun!']
  • 37. 37 4. remove() The remove() method is used to remove an element from the list. In the case of multiple occurrences of the same element, only the first occurrence is removed. Example: myList = [1, 2, 3, "EduCBA", "makes learning fun!"] myList.remove('makes learning fun!') myList.insert(4, 'makes') print(myList) Output: [1, 2, 3, 'EduCBA', 'makes']
  • 38. 38 5. pop() The method pop() can remove an element from any position in the list. The parameter supplied to this method is the index of the element to be removed. Example: myList = [1, 2, 3, "EduCBA", "makes learning fun!"] myList.pop(4) myList.insert(4, 'makes') myList.insert(5, 'learning') myList.insert(6, 'so much fun!') print(myList) Output: [1, 2, 3, 'EduCBA', 'makes', 'learning', 'so much fun!']
  • 39. 39 6. Slice The Slice operation is used to print a section of the list. The Slice operation returns a specific range of elements. It does not modify the original list. Example: myList = [1, 2, 3, "EduCBA", "makes learning fun!"] print(myList[:4]) # prints from beginning to end index print(myList[2:]) # prints from start index to end of list print(myList[2:4]) # prints from start index to end index print(myList[:]) # prints from beginning to end of list Output: [1, 2, 3, 'EduCBA'] [3, 'EduCBA', 'makes learning fun!'] [3, 'EduCBA'] [1, 2, 3, 'EduCBA', 'makes learning fun!']
  • 40. 40 7. Reverse() The reverse() operation is used to reverse the elements of the list. This method modifies the original list. To reverse a list without modifying the original one, we use the slice operation with negative indices. Specifying negative indices iterates the list from the rear end to the front end of the list. Example: myList = [1, 2, 3, "EduCBA", "makes learning fun!"] print(myList[::-1]) # does not modify the original list myList.reverse() # modifies the original list print(myList) Output: ['makes learning fun!', 'EduCBA', 3, 2, 1] ['makes learning fun!', 'EduCBA', 3, 2, 1]
  • 41. 41 8. len() The len() method returns the length of the list, i.e. the number of elements in the list. Example: myList = [1, 2, 3, "EduCBA", "makes learning fun!"] print(len(myList)) Output: 5 9. min() & max() The min() method returns the minimum value in the list. The max() method returns the maximum value in the list. Both the methods accept only homogeneous lists, i.e. list having elements of similar type. Example: myList = [1, 2, 3] print(min(myList))
  • 42. 42 10. count() The function count() returns the number of occurrences of a given element in the list. Example: myList = [1, 2, 3] print(myList.count(3)) 11. index() The index() method returns the position of the first occurrence of the given element. It takes two optional parameters – the begin index and the end index. These parameters define the start and end position of the search area on the list. When supplied, the element is searched only in the sub-list bound by the begin and end indices. When not supplied, the element is searched in the whole list. Example: myList = [1, 2, 3,"EduCBA"] print(myList.index('EduCBA')) # searches in the whole list print(myList.index('EduCBA', 0, 2)) # searches from 0th to 2nd position
  • 43. 43 12. sort() The sort method sorts the list in ascending order. This operation can only be performed on homogeneous lists, i.e. lists having elements of similar type. Example: yourList = [4, 2, 6, 5, 0, 1] yourList.sort() print(yourList) 13. clear() This function erases all the elements from the list and empties it. Example: yourList = [4, 2, 6, 5, 0, 1] yourList.clear() print(yourList)
  • 48. # Different types of tuples # Empty tuple my_tuple = () print(my_tuple) # Tuple having integers my_tuple = (1, 2, 3) print(my_tuple) # tuple with mixed datatypes my_tuple = (1, "Hello", 3.4) print(my_tuple) # nested tuple my_tuple = ("mouse", [8, 4, 6], (1, 2, 3)) print(my_tuple) () (1, 2, 3) (1, 'Hello', 3.4) ('mouse', [8, 4, 6], (1, 2, 3))
  • 49. A tuple can also be created without using parentheses. This is known as tuple packing. my_tuple = 3, 4.6, "dog" print(my_tuple) # tuple unpacking is also possible a, b, c = my_tuple print(a) # 3 print(b) # 4.6 print(c) # dog Output (3, 4.6, 'dog’) 3 4.6 dog
  • 50. cess Tuple Elements ere are various ways in which we can access the elements of a tuple. ndexing can use the index operator [] to access an item in a tuple, ere the index starts from 0. a tuple having 6 elements will have indices from 0 to 5. ing to access an index outside he tuple index range(6,7,... in this example) raise an IndexError. e index must be an integer, we cannot use float or other types. is will result in TypeError. # Accessing tuple elements using indexing my_tuple = ('p','e','r','m','i','t') print(my_tuple[0]) # 'p' print(my_tuple[5]) # 't' # IndexError: list index out of range # print(my_tuple[6]) # Index must be an integer # TypeError: list indices must be integers, not float # my_tuple[2.0] # nested tuple n_tuple = ("mouse", [8, 4, 6], (1, 2, 3)) # nested index print(n_tuple[0][3]) # 's' print(n_tuple[1][1]) # 4 Output P t S 4
  • 51. 2. Negative Indexing Python allows negative indexing for its sequences. The index of -1 refers to the last item, -2 to the second last item and so on. # Negative indexing for accessing tuple elements my_tuple = ('p', 'e', 'r', 'm', 'i', 't') # Output: 't' print(my_tuple[-1]) # Output: 'p' print(my_tuple[-6])
  • 52. 3. Slicing We can access a range of items in a tuple by using the slicing operator colon : # Accessing tuple elements using slicing my_tuple = ('p','r','o','g','r','a','m','i','z') # elements 2nd to 4th # Output: ('r', 'o', 'g') print(my_tuple[1:4]) # elements beginning to 2nd # Output: ('p', 'r') print(my_tuple[:-7]) # elements 8th to end # Output: ('i', 'z') print(my_tuple[7:]) # elements beginning to end # Output: ('p', 'r', 'o', 'g', 'r', 'a', 'm', 'i', 'z') print(my_tuple[:]) Output ('r', 'o', 'g’) ('p', 'r’) ('i', 'z’) ('p', 'r', 'o', 'g', 'r', 'a', 'm', 'i', 'z')
  • 57. Changing a Tuple Unlike lists, tuples are immutable. This means that elements of a tuple cannot be changed once they have been assigned. But, if the element is itself a mutable data type like a list, its nested items can be changed. We can also assign a tuple to different values (reassignment). # Changing tuple values my_tuple = (4, 2, 3, [6, 5]) # TypeError: 'tuple' object does not support item assignment # my_tuple[1] = 9 # However, item of mutable element can be changed my_tuple[3][0] = 9 # Output: (4, 2, 3, [9, 5]) print(my_tuple) # Tuples can be reassigned my_tuple = ('p', 'r', 'o', 'g', 'r', 'a', 'm', 'i', 'z') # Output: ('p', 'r', 'o', 'g', 'r', 'a', 'm', 'i', 'z') print(my_tuple) Output (4, 2, 3, [9, 5]) ('p', 'r', 'o', 'g', 'r', 'a', 'm', 'i', 'z')
  • 59. Other Tuple Operations 1. Tuple Membership Test We can test if an item exists in a tuple or not, using the keyword in. # Membership test in tuple my_tuple = ('a', 'p', 'p', 'l', 'e',) # In operation print('a' in my_tuple) print('b' in my_tuple) # Not in operation print('g' not in my_tuple) Output True False True
  • 61. #!/usr/bin/python tuple1, tuple2 = (123, 'xyz', 'zara'), (456, 'abc’) print "First tuple length : ", len(tuple1) print "Second tuple length : ", len(tuple2) #!/usr/bin/python3tuple1, tuple2 = ('maths', 'che', 'phy', 'bio'), (456, 700, 200) print ("Max value element : ", max(tuple1)) print ("Max value element : ", max(tuple2)) #!/usr/bin/python3tuple1, tuple2 = ('maths', 'che', 'phy', 'bio'), (456, 700, 200) print ("Max value element : ", min(tuple1)) print ("Max value element : ", min(tuple2)) # when an iterable(e.g., list) is passed list1= [ 1, 2, 3, 4 ] tuple2 = tuple(list1) print(tuple2)
  • 63. # initializing list test_list = [(4, 6), (1, 2), (9, 2), (2, 1), (5, 7), (6, 4), (9, 2)] # printing original list print("The original list is : " + str(test_list)) # using map() to get all sorted # set removes duplicates res = list({*map(tuple, map(sorted, test_list))}) # printing result print("Tuples after removal : " + str(res)) Python Program to Remove duplicate tuples irrespective of order runfile('D:/python examples/untitled6.py', wdir='D:/python examples') The original list is : [(4, 6), (1, 2), (9, 2), (2, 1), (5, 7), (6, 4), (9, 2)] Tuples after removal : [(2, 9), (1, 2), (4, 6), (5, 7)]
  • 64. # initializing lists test_list = [(3, -1), (-4, -3), (1, 3), (-2, 5), (-4, 2), (-9, -3)] # printing original list print("The original list is : " + str(test_list)) res = [] for sub in test_list: # 2nd element converted to negative magnitude res.append((abs(sub[0]), -abs(sub[1]))) # printing result print("Updated Tuple list : " + str(res)) Change the signs of elements of tuples in a list Output: The original list is : [(3, -1), (-4, -3), (1, 3), (-2, 5), (-4, 2), (-9, -3)] Updated Tuple list : [(3, -1), (4, -3), (1, -3), (2, -5), (4, -2), (9, -3)]
  • 65. Python program to Sort a List of Tuples in Increasing Order by the Last Element in Each Tuple e task is to write a Python Program to sort a list of tuples in increasing order by the last element in each tuple. put: [(1, 3), (3, 2), (2, 1)] tput: [(2, 1), (3, 2), (1, 3)] planation: sort tuple based on the last digit of each tuple. Methods #1: Using sorted(). Sorted() method sorts a list and always returns a list with the elements in a sorted manner, without modifying the original sequence. Approach: •Take a list of tuples from the user. •Define a function that returns the last element of each tuple in the list of tuples. •Define another function with the previous function as the key and sort the list. •Print the sorted list. •Python3 def last(n): return n[-1] def sort(tuples): return sorted(tuples, key=last) a=[(1, 3), (3, 2), (2, 1)] print("Sorted:") print(sort(a))
  • 67. sets
  • 69. A set is an unordered collection of items. Every set element is unique (no duplicates) and must be immutable (cannot be changed). However, a set itself is mutable. We can add or remove items from it. Sets can also be used to perform mathematical set operations like union, intersection, symmetric difference, etc. reating Python Sets set is created by placing all the items (elements) inside curly braces {}, separated by comma, r by using the built-in set() function. can have any number of items and they may be of different types (integer, float, tuple, string etc.). ut a set cannot have mutable elements like lists, sets or dictionaries as its elements.
  • 70. # Different types of sets in Python # set of integers my_set = {1, 2, 3} print(my_set) # set of mixed datatypes my_set = {1.0, "Hello", (1, 2, 3)} print(my_set) Output {1, 2, 3} {1.0, (1, 2, 3), 'Hello'}
  • 71. # set cannot have duplicates # Output: {1, 2, 3, 4} my_set = {1, 2, 3, 4, 3, 2} print(my_set) # we can make set from a list # Output: {1, 2, 3} my_set = set([1, 2, 3, 2]) print(my_set) # set cannot have mutable items # here [3, 4] is a mutable list # this will cause an error. my_set = {1, 2, [3, 4]} {1, 2, 3, 4} {1, 2, 3} Traceback (most recent call last): File "<string>", line 15, in <module> my_set = {1, 2, [3, 4]} TypeError: unhashable type: 'list'
  • 72. ating an empty set is a bit tricky. pty curly braces {} will make an empty dictionary in Python. make a set without any elements, we use the set() function without any argument. # Distinguish set and dictionary while creating empty set # initialize a with {} a = {} # check data type of a print(type(a)) # initialize a with set() a = set() # check data type of a print(type(a)) Output <class 'dict’> <class 'set'>
  • 73. Modifying a set in Python Sets are mutable. However, since they are unordered, indexing has no meaning. We cannot access or change an element of a set using indexing or slicing. et data type does not support it. We can add a single element using the add() method, and multiple elements using the update() method. The update() method can take tuples, lists, strings or other sets as its argument. In all cases, duplicates are avoided.
  • 74. # initialize my_set my_set = {1, 3} print(my_set) # my_set[0] # if you uncomment the above line # you will get an error # TypeError: 'set' object does not support indexing # add an element # Output: {1, 2, 3} my_set.add(2) print(my_set) # add multiple elements # Output: {1, 2, 3, 4} my_set.update([2, 3, 4]) print(my_set) # add list and set # Output: {1, 2, 3, 4, 5, 6, 8} my_set.update([4, 5], {1, 6, 8}) print(my_set) Output {1, 3} {1, 2, 3} {1, 2, 3, 4} {1, 2, 3, 4, 5, 6, 8}
  • 75. Removing elements from a set A particular item can be removed from a set using the methods discard() and remove(). The only difference between the two is that the discard() function leaves a set unchanged if the element is not present in the set. On the other hand, the remove() function will raise an error in such a condition (if element is not present in the set). The following example will illustrate this. # Difference between discard() and remove() # initialize my_set my_set = {1, 3, 4, 5, 6} print(my_set) # discard an element # Output: {1, 3, 5, 6} my_set.discard(4) print(my_set) # remove an element # Output: {1, 3, 5} my_set.remove(6) print(my_set) # discard an element # not present in my_set # Output: {1, 3, 5} my_set.discard(2) print(my_set) # remove an element # not present in my_set # you will get an error. # Output: KeyError my_set.remove(2) Output {1, 3, 4, 5, 6} {1, 3, 5, 6} {1, 3, 5} {1, 3, 5} Traceback (most recent call last): File "<string>", line 28, in <module> KeyError: 2
  • 76. milarly, we can remove and return an item using the pop() method. nce set is an unordered data type, there is no way of determining which item will be popped. is completely arbitrary. e can also remove all the items from a set using the clear() method. # initialize my_set # Output: set of unique elements my_set = set("HelloWorld") print(my_set) # pop an element # Output: random element print(my_set.pop()) # pop another element my_set.pop() print(my_set) # clear my_set # Output: set() my_set.clear() print(my_set) print(my_set) {'H', 'l', 'r', 'W', 'o', 'd', 'e’} H {'r', 'W', 'o', 'd', 'e’} set()
  • 77. Python Set Operations Sets can be used to carry out mathematical set operations like union, intersection, difference and symmetric difference. We can do this with operators or methods. Let us consider the following two sets for the following operations. >>> A = {1, 2, 3, 4, 5} >>> B = {4, 5, 6, 7, 8} Set Union Set Union in Python Union of and A B is a set of all elements from both sets. Union is performed using | operator. Same can be accomplished using th e union() method. # Set union method # initialize A and B A = {1, 2, 3, 4, 5} B = {4, 5, 6, 7, 8} # use | operator # Output: {1, 2, 3, 4, 5, 6, 7, 8} print(A | B) Output
  • 78. {1, 2, 3, 4, 5, 6, 7, 8} Try the following examples on Python shell. # use union function >>> A.union(B) {1, 2, 3, 4, 5, 6, 7, 8} # use union function on B >>> B.union(A) {1, 2, 3, 4, 5, 6, 7, 8} Set Intersection Set Intersection in Python Intersection of sets. A and is a set of elements that are common in both the B Intersection is performed using & operator. Same can be accomplished using theintersection() method. # Intersection of sets # initialize A and B A = {1, 2, 3, 4, 5} B = {4, 5, 6, 7, 8}
  • 79. # use intersection function on A >>> A.intersection(B) {4, 5} # use intersection function on B >>> B.intersection(A) {4, 5} Set Difference Set Difference in Python Difference of the set B from set A(A - B) is a set of elements that are only in but not in B. Similarly, A B - is a set of elements in A B but not in A. # use & operator # Output: {4, 5} print(A & B) Output {4, 5} Try the following examples on Python shell.
  • 80. Difference is performed using the difference() method. - operator. Same can be accomplished using # Difference of two sets # initialize A and B A = {1, 2, 3, 4, 5} B = {4, 5, 6, 7, 8} # use - operator on A # Output: {1, 2, 3} print(A - B) Output {1, 2, 3} Try the following examples on Python shell. # use difference function on A >>> A.difference(B) {1, 2, 3} # use - operator on B >>> B - A {8, 6, 7} # use difference function on B >>> B.difference(A) {8, 6, 7} Set Symmetric Difference
  • 81. Set Symmetric Difference in Python Symmetric Difference of A and B is a set of elements in A and but not in B both (excluding the intersection). Symmetric difference is performed using operator. Same can be ^ accomplished using the method symmetric_difference(). # Symmetric difference of two sets # initialize A and B A = {1, 2, 3, 4, 5} B = {4, 5, 6, 7, 8} # use ^ operator # Output: {1, 2, 3, 6, 7, 8} print(A ^ B) Output {1, 2, 3, 6, 7, 8} Try the following examples on Python shell. # use symmetric_difference function on A >>> A.symmetric_difference(B) {1, 2, 3, 6, 7, 8} # use symmetric_difference function on B >>> B.symmetric_difference(A) {1, 2, 3, 6, 7, 8}
  • 82. Other Python Set Methods There are many set methods, some of which we have already used above. Here is a list of all the methods that are available with the set objects: Method Description add() Adds an element to the set clear() Removes all elements from the set copy() Returns a copy of the set difference() Returns the difference of two or more sets as a new set difference_update() Removes all elements of another set from this set discard() Removes an element from the set if it is a member. (Do nothing if the element is not in set) intersection() Returns the intersection of two sets as a new set intersection_update() Updates the set with the intersection of itself and another isdisjoint( ) Returns if two sets have a null intersection Tru e issubset() Returns if another set contains this set Tru e issuperset() Returns if this set contains another set Tru e pop() Removes and returns an arbitrary set element. Raises KeyError if the set is empty remove() Removes an element from the set. If the element is not a member, raises a KeyError symmetric_difference() Returns the symmetric difference of two sets as a new set symmetric_difference_update( ) Updates a set with the symmetric difference of itself and
  • 83. another union() Returns the union of sets in a new set update() Updates the set with the union of itself and others Other Set Operations Set Membership Test We can test if an item exists in a set or not, using the in keyword. Iterating Through a Set # in keyword in a set # initialize my_set my_set = set("apple") # check if 'a' is present # Output: True print('a' in my_set) # check if 'p' is present # Output: False print('p' not in my_set) Output True False We can iterate through each item in a set using a for loop. >>> for letter in set("apple"):
  • 84. .. . .. . a p e l print(lette r) Built-in Functions with Set Built-in functions like all(), any(), enumerate(), len(), max(), min(), sorted(), sum( ) etc. are commonly used with sets to perform different tasks. Function Description all() Returns if all elements of the set are true (or if the set is empty). Tru e any() Returns if any element of the set is true. If the set is empty, returns False. Tru e enumerate() Returns an enumerate object. It contains the index and value for all the items of the set as a pair. len() Returns the length (the number of items) in the set. max() Returns the largest item in the set. min() Returns the smallest item in the set. sorted() Returns a new sorted list from elements in the set(does not sort the set itself). sum() Returns the sum of all elements in the set. Python Frozenset
  • 85. Frozenset is a new class that has the characteristics of a set, but its elements cannot be changed once assigned. While tuples are immutable lists, frozensets are immutable sets. Sets being mutable are unhashable, so they can't be used as dictionary keys. On the other hand, frozensets are hash able and can be used as keys to a dictionary. Frozensets can be created using the frozenset() function. This data type supports methods like copy(), difference(), intersection(), isdisjoint(), issubset(), issuperset ( ), symmetric_difference () and union(). Being immutable, it does not have methods that add or remove elements. # Frozensets # initialize A and B A = frozenset([1, 2, 3, 4]) B = frozenset([3, 4, 5, 6]) Try these examples on Python shell. >>> A.isdisjoint(B) False >>> A.difference(B) frozenset({1, 2}) >>> A | B frozenset({1, 2, 3, 4, 5, 6}) >>> A.add(3) ... AttributeError: 'frozenset' object has no attribute 'add'