Unit 3 Collection and Sequences Chapter 3 (5 August) Final
Unit 3 Collection and Sequences Chapter 3 (5 August) Final
PYTHON COLLECTION/SEQUENCES
Authors Gopal Gupta, Harsh Khatter, Shelley Gupta, Poonam Rana, Aatif
Jamshed, Anurag Mishra
Authorized by
Creation/Revision Date May 2021 ,August 2021
Version 1.0
Contents
3. Introduction to collections/sequences data types ........................................................................... 4
3.1 String ................................................................................................................................................ 5
3.1.1 Creation of String ...................................................................................................................... 6
3.1.2 Accessing Strings ....................................................................................................................... 6
3.1.3 Updation / Deletion................................................................................................................. 11
3.1.4 Built-In Method ....................................................................................................................... 12
3.1.5 Basic Operations...................................................................................................................... 16
3.1.6 String Formatters .................................................................................................................... 17
3.1.7 Loop with String ...................................................................................................................... 21
3.2. List ................................................................................................................................................. 23
3.2.1. Creation .................................................................................................................................. 25
3.2.2. Accessing ................................................................................................................................ 25
3.2.3. Update. ................................................................................................................................... 28
3.2.4. Built-in method ...................................................................................................................... 31
3.2.5. Operations with list ................................................................................................................ 32
3.2.6. Loops ...................................................................................................................................... 34
3.2.7 Nested List ............................................................................................................................... 35
3.2.8 List Comprehension ................................................................................................................. 37
3.3 Tuple .............................................................................................................................................. 38
3.3.1 Creation of Tuple ..................................................................................................................... 39
3.3.2 Accessing Tuple ....................................................................................................................... 41
3.3.3 Modification/ Updating a Tuple .............................................................................................. 43
3.3.4 Built-in Methods in Dictionary ................................................................................................ 43
3.3.5 Operations on Tuple ................................................................................................................ 44
3.4 Dictionaries .................................................................................................................................... 46
3.4.1 Creation of Dictionary ............................................................................................................. 48
3.4.2 Accessing of Dictionary ........................................................................................................... 49
3.4.3 Modification in Dictionary ....................................................................................................... 51
3.4.4 Nested Dictionary .................................................................................................................... 53
3.4.5 Built-in Methods in Dictionary ................................................................................................ 53
3.3.6 Loops and conditions on dictionaries ...................................................................................... 55
3.5 Set .................................................................................................................................................. 58
3.5.1 Creation ................................................................................................................................... 59
3.5.2 Accessing ................................................................................................................................. 62
3.5.3 Modification ............................................................................................................................ 62
3.5.4 Built-in-methods ..................................................................................................................... 64
3.5.5 Operators ................................................................................................................................ 68
3.5.6 Loops ....................................................................................................................................... 74
3.5.7 Frozen Set................................................................................................................................ 75
3.6 Summary ........................................................................................................................................ 77
References: .......................................................................................................................................... 78
3. Introduction to collections/sequences data types
In chapter 1, we have seen some primitive data type like: integer, float and complex. These
data types are used to represent the single value numeric data and in chapter 2, we have
learnt to apply condition, loop on this type of data but in real life we need to store data like-
All collection data types in python have rich variety of built-in method and associated
operation.
Built-in method are such functions or procedure which provides us to use as plug and play,
we do not have to implement it.
3.1 String
Suppose we want to store a name of college, About the college or Address of college then we
choose String data type. A string is a sequence of alphanumeric and special character.
For example - 'abes', 'Computer Science', '123', 'NH-24, Delhi Hapur Bypass' are the string.
String is the collection of characters, it may compose of alphanumeric and special characters.
In Python, Strings are created in many ways using single quotes or double-quotes.
Note - Python does not have char data type, so if we have to take one char variable so it
means we have to take a string of length 1.
This section discusses about the string in python, operations and built-in methods on string.
3.1.1 Creation of String
Empty String
An empty string is a string having no character. We have three ways to create an empty
string as shown in syntax.
Syntax –
In Figure 3.1.1(a), an empty string is created by using single quotes, double quotes and str().
In Figure 3.1.1(b), a non-empty string is created by using single quotes and double quotes.
Syntax –
Positive Indexing
In python positive indexing start from Zero (0) and from left hand side i.e. first character
store at index 0, second at index 1 and so on.
As shown in figure 3.1.2(a) positive indexing start from left-hand side and start from Zero
(0). Every character of string has some index value.
Negative Indexing
In python negative indexing start from -1 and from right-hand side i.e. Last character store at
index -1 and as we move towards the left, it keeps increasing like -2, -3, and so on, as shown
in Figure 3.1.2(b).
In the above example index of 'L’ is 2(positive) and -11 (negative), index of 'P' is 7(positive)
and -6 (negative).
Note – We can use both positive and negative indexing to access any element/ character from string.
We have already seen that using [], we can access string characters by giving indexes if we
use colon inside square bracket like [:] it becomes a slicing operator in Python.
String slicing is the way of selection of substring, as shown in figure 3.1.2(c). String 'Like' is
substring in given 'I Like Python' string.
st[ 2 : 6 : -1 ] Section **
Output – Empty string
Note – *, **
• * When start index is missing it will start from either first character or from last. It
depends on step sign (positive or negative).
• * When end index is missing it will execute till last character or first character. It
depends on step sign (positive or negative).
• * When we take negative steps it will scan from start to end in opposite direction.
• ** In the case of step is positive or negative the slicing will be done as below given
algorithm.
Practice Questions:
1. Write a program to reverse a string and check it is palindrome or not.
2. Write a program to capitalize the first and last character of each word in a string.
Updation
In above Example 1, as we can see, the string does not allow assigning a new element,
because item assignment does not support by string.
Deletion
We can’t reassign the string characters but we can delete the complete string using del
command as shown in the example 2.
As we can see in the example 2, after deletion when we try to print the string st it gives
NameError : st not defined.
Note - There are few generic built-in methods which are not called by dot operator. These methods
are used by all collection (string, list, tuple, set etc.) in python. These methods are called by their
name and we pass collection as argument.
islower()
isupper()
Isdigit()
Practice Questions:
1. Write a program to remove ith character from a given string.
2. Write a program to find a string contains only alphabets.
Strings in Python support basic operations like concatenation, replication and membership.
• Concatenation means joining/combining two string into one.
• Replication means repeating same string multiple times.
• Membership tells a given string is member of another string or not.
All Operations are being summarized in the following table 3.1.5.
+
It will merge/join second string at
the end of first string and return.
Multiply (Replicas)
It will repeat same string multiple
* times and return.
Note – multiply string only with
integer number.
Membership
It will check a given substring is
For different types of requirement to print the string in a formatted manner; here, format
implies that in what look and feel we want our strings to get printed; python string provides
a number of options for formatting.
Table 3.1.6(a): String format style
Escape Explanation Example
sequence
Ignores newline
\newline
Backslash
\\
Write a backslash in string
Newline
\n
We can also use keywords arguments in format method, as shown in the following example,
as shown in figure 3.1.6(c).
We can also use format specifier in format method like in language ‘C’. Format specifier are
used to do following –
• Represent value of amount = 12.68456 at two decimal place
• Represent value of integer in Binary, Octal or Hexadecimal etc.
Syntax -
X or x
Fstring is the way of formatting as format method does but in an easier way. We include ‘f’
or ‘F’ as a prefix of string as shown in below example.
Figure 3.1.6(e): Usage of fstring
Strings are sequence of character and iterable objects, so we can directly apply for loop
through string.
Example 1 - Scan/Iterate each character of string through index using for loop.
In the above example, with the help of range () function first generate sequence of index and
apply loop.
Example 2 - Scan/Iterate each character of string directly using for loop.
In the above example, for loop apply directly to string st. for loop iterate using ‘val’ variable
and each character is referring one by one via val. Using print statement, we print the value
of val.
Example 3 – Write a program to print number of alphabets and digits in a given string.
Example 4 – To add 'ing' at the end of a given string (length should be at least 3). If the given
string already ends with 'ing' then add 'ly' instead. If the string length of the given string is less
than 3, leave it unchanged.
Sample String : 'abc' Sample String : 'string'
Expected Result : 'abcing' Expected Result : 'stringly'
Practice Questions:
1. Write a program to find the frequency of vowels in a given string.
2. Write a program to find number of special symbol in a given string. Whitespace
should be ignored.
3.2. List
In Python List is the most commonly used sequence. Important points about list are as
follows.
• List elements are enclosed in square brackets [] and are comma separated.
• List is the sequence of class type ‘list’.
• List can contain elements of different data types.
• List is a mutable(changeable) sequence, would be discussed in detail in 3.2.3
• List allows duplicate elements.
• List elements are ordered, it means it give specific order to the elements, if new
element is added, by default it comes at the end of the list.
List is used when there is a possibility of elements of different data type, for example record
of a particular student, having name as string, roll.no as integer, marks as float, father’s
name as string. To contain this record list is the appropriate sequence.
Figure 3.2: List representation
List example
In this example a variable named listexample has been created and three elements have
been assigned. As we have enclosed elements in square brackets, this makes listexample is
of type list.
Ordered sequence of the list means the order in which elements appear is unique and the
position of every element is fixed; if we change the position of any element, then list would
not be the same anymore. Let's verify this with an example.
3.2.1. Creation
List can be created in many ways as follows
Empty list
As shown in following example, we can create empty list using following two methods.
3.2.2. Accessing
List elements are accessed using indexes.
• Indexing
In the list index are started from 0, it means first element takes 0 index and it
increases like 0,1,2…(n-1). List also supports negative indexing, it means last element
can be accessed using -1 index, second last as -2 and so on. These indexes are as
shown in figure 3.2.1.
Figure 3.2.1 Positive and Negative indexes in the list
• Slicing
As we have seen in the string section that slicing is used to get substring from a
string. We use Slice operator in the list to get a sub list.
Syntax of slicing
3.2.3. Update.
List updating involves insertion of new elements, deletion of elements or deletion of
complete list.
Mutable
List is a mutable sequence it means it allows changes in the elements of list as shown in
figure 3.2.3
Figure 3.2.3 Mutability Vs Immutability
We can add elements to the existing list using append function. Append function always add
the element at the end of the list.
Syntax:
Example: In this example element 5 has been appended in the originally existed list. It’s
being added in the last.
Value of the element at index 3 has been assigned new value as 5, so element in the output
list is changed from 4 to 5
Deletion from list
Example:
In this example list element has been deleted using del and remove.
In following example list1 has been deleted and then we are trying to print it and its giving
error because it does not exist now.
3.2.4. Built-in method
Python provides many built-in functions for different useful functionalities.
Solution:
Practice Exercise
1. Take a list input from user having integer elements and calculate sum and average
of the list.
2. Take an input list and swap string elements of the list with empty string.
3.2.6. Loops
We discussed loops in chapter 2. Now we would see how loop works with List sequence.
Using while loop we can read the elements of list as shown in following example
Let’s see how list elements can be accessed using for loop
We can clearly see in both the above examples that for loop requires less effort in printing
element in comparison of while loop.
Example Exercise with Solution
Solution:
Practice Exercise:
In this example, first [1] denotes [3,4] and second [1] represents 4, so it gives output as 4.
Nested List as a Matrix
We can represent nested list as matrix also. For this we would use nested for loop. Outer
loop would run for number of elements in the list and inner loop would consider individual
element of the nested list as a list.
In this example value of outer loop is running three times and value of i is 0,1 and 2 while
inner loop element is being accessed using j which takes values 0,1 and 2.
Solution:
Practice Exercise:
Python provide us writing iterative programs in much lesser lines called List comprehension.
The same problem has been solved using list comprehension.
Syntax:
We can add if-else as shown in the example, we should notice one change that because in if-
else case output is separated based on the condition, if-else and conditions has been
written along with statements.
Example Exercise with Solution
Exercise: Add 30 to every element of an integer type list if its odd and add 40 if it’s even
Solution:
Practice Exercise:
1. Convert each element of a given list of type string into upper case using list
comprehension.
2. Calculate cube of every element of integer type list using list comprehension.
3.3 Tuple
Generally, when we have data to process, it is not required to modify the data values. Take
an example of week days, here the days are fixed. So, it is better to store the values in the
data collection, where modification is not required.
Figure 3.3 Tuple Representation
In the above figure 3.3, the round brackets are used to define a tuple. If we want to change
any of the index value in tuple, this is not allowed and throw an error.
Empty Tuple:
Syntax:
In above example, the () round brackets are used to create the variable of tuple type. We
can also call the class to create a tuple object as shown in example below.
Syntax:
In above example 1, If you want to create a tuple with single value, it is required to add a
comma after the single value as shown in the above example c=(‘college’,). If the comma is
not placed, then the single value a= (1) or b=(ABES) will be treated as an independent value
instead of the data collection.
Tuple can also be created without using parenthesis; it is known as packing, as shown in the
example.
Unpacking is called when the multiple variables is assigned to a tuple; then these variables
take corresponding values.
Practice Questions:
In above example 2: tuple tuple_days carries the day’s data in it. If we can fetch the index 0
by using print(tuple_days[0])
Basically, the -1 index will return the last value of tuple. Indexes start from zero, and it goes
up to a number of elements or say -1. Take another example to fetch the -1 index from
tuple.
Slicing in a tuple is like a list that extracts a part of the tuple from the original tuple.
Practice Questions:
• Write a Python program to get the 4th element and 4th element from last of a
tuple.
• Write a Python program to check whether an element exists within a tuple.
The list of operations allowed on tuple which are frequently used are shown below in form
of table:
Add two
Concatenation
tuples
Creates
Multiplication copies of the
tuple
To check
whether an
Membership element
belong to
tuple or not
Would return
Not true if
element does
Membership
not belong to
tuple.
Practice Questions
• Write a Python program to count the elements in a list until an element is a tuple.
• Write a Python program to calculate the average value of the numbers in a given
tuple of tuples
Example1: Take the tuple named tuple_days and print all its elements.
In above example 1: The elements are printed while iterating through for loop condition for
in tuple_days and then we print the values of i in each iteration.
Example2: Let have a look to the example where we are placing a condition to return the
values having word length greater than 3.
In above example 2: The elements are printed while iterating through for loop condition for
in tuple_days and then we print the values of i in each iteration with the condition if(len(i)>3)
To show the comparison between list and tuple, have a look to the table below:
Practice Questions:
• Write a Python program to convert a tuple of string values to a tuple of integer values
• Write a Python program to convert a given tuple of positive integers into an integer.
3.4 Dictionaries
Dictionary is a unique data collection of Python which stores the key-value pair.
In the list, the values are stored based on the integer default indexes. The indexes are by
default and start with index 0. As the list shown in figure 3.4(a), the indexes and values of the
list are mentioned.
By default,
indexing in list
In above example, 0,1,2,3,4 are the by default indexes and 1219, “harsh”, “M”, “CSE-2”,
“ABES” are the corresponding values in the list. If I talk about the value 1219, user is unaware
about the value, what exactly 1219 is? Is it a roll number, or faculty number, or library card
number! So, it is better to have an attribute name which represents the value.
Dictionary provides the solution to the above problem. The user can add an element by giving
a user-defined index called a key. And the key and its corresponding value makes the key-
value pair in dictionary. This key-value pair is considered as one item in dictionary.
Figure 3.4(b) shows the dictionary orientation where on the left side, keys are present
concerning the values on the right side of the figure.
In dictionaries, the indexes are not by default. Users can create its customize indexes named
as keys and store their respective values. Here in the above example, dictionary has three
key-value pairs. “Emp code” is the key and its value is 1219. “Name” is a key, and its value is
“Harsh”. These key-value pairs is written as {“Emp code”: 1219, “Name”: “Harsh”, “College”:
“ABES”}.
Empty Dictionary
Syntax
In above example 1, dict is used to create empty dictionary when we print the dictionary, it
will represent a blank dictionary with symbol {}.
Non-Empty Dictionary
Syntax
In the above example 1, dictionary creation with keys: name, empcode and subject and their
values.
Example 1: Write a program to access element values from a dictionary using element keys.
In above example 1 a dictionary d is created with key value pairs. If you want to fetch the first
value i.e. ‘Harsh’, so you need to mention the key of the value like d[‘name’], here the name
variable is in string format so quotes are required; without quotes, the statement will give an
error.
If the syntax is like a list, where the index is used to get the element value, i.e. dic1[0], it will
give a key error. Here, the value will be retrieved from dic1["a"].
The accessing style in list and dictionary is different. If we compare the functionalities of list
and dictionary, then the outcome is shown in figure 3.4.2(a).
List Dictionary
When we store some values in the collection, we must need a liberty to modify or update its
value. In dictionary, we have an option to modify or update the values. The values can be
easily changed by giving the key as index with dictionary name.
Example 1:
Here the initial value of name is ‘Harsh’. If we want to change the value to ‘Harsh Khatter’,
then the key ‘name’ is to be passed in dictionary d with updated desired value.
Example 2: Take an example to swap the values of the dictionary.
Here the dictionary values are swapped by using the keys and temporary variable.
No, if we try to change the key, interpreter will create a new key. Once the keys are defined,
it is not possible to change the keys; we can change or update the values with respect to the
keys only.
Example: where we are trying to modify the existing key ‘name’ as the ‘firstname’. But instead
of updating the existing key, a new key ‘firstname’ has been added to the dictionary with
same given value ‘Harsh’.
Note:
1. In dictionary, keys are not changeable, only values are modifiable. It means
“Keys are immutable, and the values are mutable”
2. Keys are unique, and the values of the keys can be same
Here, the dictionary dt is created in such a manner where the key 3 consists of an another
dictionary. If you want to fetch the inner dictionary value, use the same concept of nested
list.
dict.fromkeys() – When the keys are already in a data sequence, and a new dictionary with
the keys from the data sequence is created with new values. Here, the below example shows
how a list of values is used as the dictionary's keys to save the data values.
dict.get() – If the key is present in the dictionary, its value is returned. If the key is not present
in a dictionary, then the default value will be shown as output instead of a KeyError. get()
method has an option to add a default value.
dict.update() – this adds the one dictionary with another dictionary. Here in the example, the
dictionary dict2 is added to dict1 dictionary.
dict.pop() - The pop() method takes an argument as the dictionary key, and deletes the item
from the dictionary.
dict.popitem() - The popitem() method retrieves and removes the last key/value pair inserted
into the dictionary.
Loops and conditions can easily apply to dictionaries. Let's look at the loop and conditions in
dictionary.
57
3.5 Set
A set is another data collection data types in python, which stores unique elements in an
unordered way.
Ordered Unordered
1.Item 1 1. Item 2
2. Item 2 2. Item 5
3. Item 3 3. Item 1
4. Item 4 4. Item 3
5. Item 5 5. Item 4
Scenario 1: In ABES Engineering college, we have different sets of rules which have to follow
by every student and employee. There are disciplinary rules, rules for leave, hostel rules,
Timing rules, and many others. Hence, all different types of rules are separated from others
and can be stored in the form of set.
Scenario 2: When we visit any shopping mall, we all have noticed that there are separate
portions or sections for each kind of things. For instances, clothing shops are on another floor
whereas the food court is at another floor of the mall so these categories can be considered
as sets.
Scenario 3: In a class of 50 students, 35 said they loved Python, 30 said they loved Java. The
teacher wanted to know how many students loved both Python and Java, as well as those
who did not have a hobby. The teacher grouped the students who had Python and Java into
groups called sets.
Note: Sets can also be used to perform mathematical set operations like union,
intersection, symmetric difference, etc.
58
3.5.1 Creation
Empty Set
Syntax:
Set can be created using class name set () and elements can be stored in assigned set s1
object/variable as shown in a figure 3.5.1
In above example 1, an empty set is created using set() and set without any elements are
produced as output using print(s1). print(type(s1)) is used to check the class of s1 variable
/object.
Note: To define an empty set, we cannot use the curly braces {} , because dictionary also
uses curly braces to create empty dictionary.
59
Example 2: Write a program to create set using {}.
Output
In above example 2, we have tried to create empty set using {} and it returns dictionary as
output.
The elements in non-empty sets can be of any types like numbers, float, strings, Boolean etc
In Python, the elements of a non-empty sets are defined inside curly braces {} and are
separated by commas.
In above example 1, set of integers is created using curly brackets and unique elements are
produced as output.
Elements as String
Output
In above example 2, set of strings is created using curly brackets and unique elements are
produced as output.
60
Example 3: Write a program to create non empty set of different data types.
In above example 3, set of Integer, Float, strings and Boolean is created using curly brackets
and unique elements are produced as output.
We can also create non empty et using set(object), which iterates over the elements present
in object and adds all the unique elements to the set as shown in examples below.
In above example 4, set of integers in list are passed as argument in set () as an object and
unique elements are produced as output.
In above example 5, set of characters as string is passed as argument in set() as an object and
unique alphabets are produced as output.
61
3.5.2 Accessing
Python set’s item cannot be accessed using indexes. The elements in set appear in a different
order every time it is used. Due to this, set elements cannot be referred to by index.
Output
In above example 1, we try to access set_acess[2] and it will give us a Type Error (‘set’ object
does not support indexing )when using indexing.
3.5.3 Modification
Every element in a set is unique and immutable(unchangeable), i.e. no duplicate values
should be there, and the values can’t be changed.
Output
In above example we are trying modify element(set_access[2]=4), it will give type error(set
does not support item assignment).
However, we can add or remove elements from the set as the set itself is mutable.
62
We use the add () method to add a single element and update () method when multiple
elements are to be added. The elements can be of the form lists, tuples, strings, or sets in
the update () method. Duplicates are avoided in all cases.
Add() Method
Python set add () method is used to add an element to the given input set. If the element
already exists, then the add () method does not add the element.
Syntax:
In above example 2, we are trying to add new element by set_add.add(22), it will add up new
element 22 into existing set.
Update() Method
Python set update () method is used to update the current set by adding items to it from
the another set. If an item is present in both sets then only one appearance of this item
will be present in the updated set.
63
Syntax:
Practice Questions:
3.5.4 Built-in-methods
There are more than 15 Python set of built-in methods that can be used on sets. Some of the
important and frequently used methods will be discussed below.
add() and update() method have been covered already in previous section 3.5.3.
64
Clear() method
Python set clear () method is used to remove all the elements in the given input set.
Syntax:
In above example 1, we are trying to remove all elements by set1.clear(), it will remove all
the elements from the set.
Copy() method
Python set copy () method is used to copy the given input set.
Syntax:
65
Example 2: Write a program to copy all elements from a set to another set.
In above example 2, we are trying to copy all elements from set1 to set2 by set1.copy(), it will
copy all the elements from the set1 to set2.
Pop() method
Python Set pop () Method in python set is an inbuilt method which is used to removes a
random element from the set and returns the popped (removed) elements.
Syntax:
In above example 3, we are trying to remove any random element from set1 by set1.pop (),
it removed orange element from the set1.
Remove() method
Python Set remove () Method in python set is used to remove the specified element from the
given set. This method will raise an error if element does not exist in the set.
66
Syntax:
In above example 4,we are trying to remove any specific element from set1 by
set1.remove(“mango”), it removed mango element from the set1 .
Discard() method
Python set discard () method is used to remove the specified item from the given input set. It
is different from the remove () method because the remove() method will give an error if the
specified item does not exist but this method will not.
Syntax:
Method Item to be
Name deleted
67
In above example 5, we are trying to remove any specific element from set1 by
set1.discard(“mango”), it removed mango element from the set1.
Len() method
The set Len is one of the set method used to find the length of a set (total number of items)
Syntax:
Method Name of
Name set
In above example 6, we are trying to find the number of elements from set1 by len(set1), it
returns the number of elements that is 3 from the set1 .
Practice Questions:
3.5.5 Operators
Sometimes a necessity arises wherein we need to establish the relationship between two
sets. There comes the concept of set operations. If we have two sets (set1 and set2), we can
perform joint operations on both sets by either using an operator or calling a method
function.
Some of the set operations and respective method is shown in the table 3.5.5.
68
Table 3.5.5: Set Methods
1. Union:
69
In a class of 60 students, 35 said they loved Python, 30 said they loved Java. The teacher
wanted to know how many students loved Python and Java. So we will take the union of
Python and Java group sets to get the required solution.
Let two sets are set1 and set2; union operation fetches all the sets' elements. Figure
3.5.5(b,c) shown the examples of union operation and method on set1 and set2.
Output
70
2. Intersection:
In a class of 60 students, 35 said they loved Python, 30 said they loved Java. The teacher
wanted to know how many students loved both Python and Java. So we will take the
intersection of Python and Java group sets.
Python Java
Let, two sets are set1 and set2, intersection operation fetches all the common elements
in both set1 and set2. Figure 3.5.5(e,f) shown the example of intersection operation and
method.
71
Figure 3.5.5(f): Intersection () method on set1 and set2
3. Set Difference:
In a class of 60 students, 35 said they loved Python, 30 said they loved Java.The teacher
wanted to know how many students loved Python but not Java (Python -Java) and how
many students loved Java but not Python (Java-Python), so we will take the set difference
of Python and Java group sets.
Suppose you have two sets set1 and set2. The difference of set1 and set2 (set1 - set2) is
the set with all elements that are in set1 but not in set2. Consequently, (set2 - set1) is the
set with all the elements in set2 but not in set1.
To determine set differences in Python, we can use either the difference () function or the
- operator.
72
- operator to find difference among two sets
Output
4. Symmetric Difference:
In a class of 60 students, 35 said they loved Python, 30 said they loved Java. The teacher
wanted to know how many students loved Python and Java but except the students who like
both Java and Python.
73
The symmetric difference of sets A and B is the set with all elements that are in A and B
except the elements that are common in both sets. It is determined using the Python's
symmetric_difference() method or the ^ operator.
Practice Questions:
1. Write a Python program to check if a given set is superset of itself and superset of
another given set.
2. Write a Python program to find the elements in a given set that are not in another
set.
3.5.6 Loops
We cannot access items in a set by referring to an index, but we can loop through the set
items using a for loop, or ask if a specified value is present in a set, by using the in keyword.
74
Figure 3.5.6(a): For loop on set
Practice Questions:
Syntax:
75
In above example 1, an non empty set is created using set () and frozenset is created using
frozenset(set1 ).
In Figure 3.5.7(b) shows adding the element in a set using add () method we got the attribute
error while adding an element in the frozen set.
Note: Like normal sets, frozenset can also perform different operations like copy,
difference, intersection, symmetric_difference, and union.
Practice Questions:
76
3.6 Summary
There are four collection data types in the Python programming language. Table 3.6 shows
the difference between List, Tuple, Set, and Dictionary.
l = [] t=( ) d={}
77
References:
1. https://docs.python.org/3/library/math.html
2. Think Python: An Introduction to Software Design, Book by Allen B. Downey
3. Head First Python, 2nd Edition, by Paul Barry
4. Python Basics: A Practical Introduction to Python, by David Amos, Dan Bader, Joanna
Jablonski, Fletcher Heisler
5. http://javatpoint.com/
6. https://www.w3resource.com/
7. https://www.learnpython.org/en/Functions
8. https://www.datacamp.com/community/tutorials/functions-python-tutorial
9. https://data-flair.training/blogs/python-function/
78