Python I Unit Notes
Python I Unit Notes
SATHISH(PhD)
Python Introduction
Python is a general purpose, dynamic, high level and interpreted programming
language. It supports Object Oriented programming approach to develop
applications. It is simple and easy to learn and provides lots of high-level data
structures.
Python iseasy to learn yet powerful and versatile scripting language which
makes itattractive for Application Development.
Python's syntax anddynamic typing with its interpreted nature, makes it
an ideallanguage for scripting and rapid application development.
Python supportsmultiple programming pattern , including object oriented,
imperative andfunctional or procedural programming styles.
Python is not intended to work on special area such as web programming. That
is why itis known asmultipurpose because it can be used with web, enterprise,
3D CAD etc.
We don't need to use data types to declare variable because it isdynamically
typed so wecan write a=10 to assign an integer value in an integer variable.
Python makes the development and debugging fast because there is no
compilation stepincluded in python development and edit-test-debug cycle is
very fast.
Python Features
2) Expressive Language
Python language is more expressive means that it is more understandable and readable.
3) Interpreted Language
Python is an interpreted language i.e. interpreter executes the code line by line at a time.
This makes debugging easy and thus suitable for
1
PREPARED BY P. SATHISH(PhD)
beginners.
2
PREPARED BY P. SATHISH(PhD)
4) Cross-platform Language
Python can run equally on different platforms such as Windows, Linux, Unix and
Macintosh etc. So, we can say that Python is a portable language.
6) Object-Oriented Language
Python supports object oriented language and concepts of classes and objects
come intoexistence.
7) Extensible
It implies that other languages such as C/C++ can be used to compile the code
and thus itcan be used further in our python code.
Python has a large and broad library and provides rich set of module and
functions forrapid application development.
10) Integrated
Python History
3
PREPARED BY P. SATHISH(PhD)
On December 3, 2008, Python 3.0 (also called "Py3K") was released. It was
designed torectify fundamental flaw of the language.
ABC programming language is said to be the predecessor of Python language
which wascapable of Exception Handling and interfacing with Amoeba
Operating System.
Python is influenced by following programming languages:
ABC language.
Modula-3
Python Version
.
Python programming language is being updated regularly with new features and
supports.There are lots of updations in python versions, started from 1994 to
current release.
A list of python versions with its released date is given below.
4
PREPARED BY P. SATHISH(PhD)
5
PREPARED BY P. SATHISH(PhD)
Python is known for its general purpose nature that makes it applicable in almost
each domain of software development. Python as a whole can be used in any sphere of
development.
1) Web Applications
6
PREPARED BY P. SATHISH(PhD)
3) Software Development
Python is popular and widely used in scientific and numeric computing. Some
useful library and package are SciPy, Pandas, IPython etc. SciPy is group of packages of
engineering,science and mathematics.
5) Business Applications
We can use Python to develop console based applications. For example: IPython.
8) 3D CAD Applications
To create CAD application Fandango is a real application which provides full features of
CAD.
9) Enterprise Applications
Python can be used to create applications which can be used within an
Enterprise or anOrganization. Some real time applications are: OpenErp, Tryton, Picalo
etc.
There are several such applications which can be developed using Python
7
PREPARED BY P. SATHISH(PhD)
--->To start with Python, first make sure that the Python is installed on local computer.
8
PREPARED BY P. SATHISH(PhD)
9
PREPARED BY P. SATHISH(PhD)
Click the Finish button and Python will be installed on your system.
o Your Python program and executable code can reside in any directory of your
system,therefore Operating System provides a specific search path that index
the directories Operating System should search for executable code.
o The Path is set in the Environment Variable of My Computer properties:
o To set path follow the steps:
In Variable name write path and in Variable value copy path up to C://Python(i.e., path
wherePython is installed). Click Ok ->Ok.
10
PREPARED BY P. SATHISH(PhD)
11
PREPARED BY P. SATHISH(PhD)
12
PREPARED BY P. SATHISH(PhD)
8. Click on Ok button:
13
PREPARED BY P. SATHISH(PhD)
9. Click on Ok button:
14
PREPARED BY P. SATHISH(PhD)
Python Example
Python is easy to learn and code and can be execute with python interpreter. We
can alsouse Python interactive shell to test python code immediately.
A simple hello world example is given below. Write below code in a file and
savewith .py extension. Python source file has .pyextension.
hello.py
1. Python3 hello.py
Output
Python interactive shell is used to test the code immediately and does not require to
write andsave code in file.
Python code is simple and easy to run. Here is a simple Python code that will print
"Welcome toPython".
Explanation:
o Here we are using IDLE to write the Python code. Detail explanation to run code
is givenin Execute Python section.
o A variable is defined named "a" which holds "Welcome To Python".
15
PREPARED BY P. SATHISH(PhD)
o "print" statement is used to print the content. Therefore "print a" statement will
print thecontent of the variable. Therefore, the output "Welcome To Python" is
produced.
In python 3.4 version, you need to add parenthesis () in a string code to print it.
To execute Python code, we can use any approach that are given below.
1) Interactive Mode
Python provides Interactive Shell to execute code immediatly and produce output
instantly. To get into this shell, write python in the command prompt and start working
withPython.
Press Enter key and the Command Prompt will appear like:
16
PREPARED BY P. SATHISH(PhD)
commands.Eg:
2) Script Mode
Using Script Mode, we can write our Python code in a separate file of any editor in our
Operating System.
17
PREPARED BY P. SATHISH(PhD)
18
PREPARED BY P. SATHISH(PhD)
NOTE: Path in the command prompt should be location of saved file.where you have
saved yourfile. In the above case file should be saved at desktop.
Click on Start button -> All Programs -> Python -> IDLE(Python GUI)
19
PREPARED BY P. SATHISH(PhD)
Execute our Python code on the Python prompt and it will display result simultaneously.
i) Click on Start button -> All Programs -> Python -> IDLE(Python GUI)
ii) Python Shell will be opened. Now click on File -> New Window.
20
PREPARED BY P. SATHISH(PhD)
21
PREPARED BY P. SATHISH(PhD)
22
PREPARED BY P. SATHISH(PhD)
Python Variables
Python does not bound us to declare variable before using in the application. It
allows usto create variable at required time.
We don't need to declare explicitly variable in Python. When we assign any value
to thevariable that variable is declared automatically.
23
PREPARED BY P. SATHISH(PhD)
Output:
1. >>>
2. 10
3. ravi
4. 20000.67
5. >>>
Multiple Assignment
variablesEg:
1. x=y=z=50
2. print iple
3. print y
4. print z
Output:
1. >>>
2. 50
3. 50
4. 50
5. >>>
variables:Eg:
1. a,b,c=5,10,15
2. print a
3. print b
24
PREPARED BY P. SATHISH(PhD)
4. print c
Output:
1. >>>
2. 5
3. 10
4. 15
5. >>>
appears.Basic Fundamentals:
ii) Comment
sa)Tokens:
o Keywords.
o Identifiers.
o Literals.
o Operators.
Tuples:
o Tuple is another form of collection where different type of data can be stored.
o It is similar to list where data is separated by commas. Only the difference is that
list usessquare bracket and tuple uses parenthesis.
o Tuples are enclosed in parenthesis and cannot be changed.
Eg:
25
PREPARED BY P. SATHISH(PhD)
1. >>> tuple=('rahul',100,60.4,'deepak')
2. >>> tuple1=('sanjay',10)
3. >>> tuple
4. ('rahul', 100, 60.4, 'deepak')
5. >>> tuple[2:]
6. (60.4, 'deepak')
7. >>> tuple1[0]
8. 'sanjay'
9. >>> tuple+tuple1
10. ('rahul', 100, 60.4, 'deepak', 'sanjay', 10)
11. >>>
Dictionary:
o Dictionary is a collection which works on a key-value pair.
o It works like an associated array where no two keys can be same.
o Dictionaries are enclosed by curly braces ({}) and values can be retrieved by
squarebracket([]).
Eg:
1. >>> dictionary={'name':'charlie','id':100,'dept':'it'}
2. >>> dictionary
3. {'dept': 'it', 'name': 'charlie', 'id': 100}
4. >>> dictionary.keys()
5. ['dept', 'name', 'id']
6. >>>
dictionary.values()7. ['it',
'charlie', 100]
8. >>>
26
PREPARED BY P. SATHISH(PhD)
Python Keywords
Python Keywords are special reserved words which convey a special meaning to
the compiler/interpreter. Each keyword have a special meaning and a specific operation.
These keywords can't be used as variable. Following is the List of Python Keywords.
Identifiers
Identifiers are the names given to the fundamental building blocks in a program.
27
PREPARED BY P. SATHISH(PhD)
Python Literals
I. String literals:
String literals can be formed by enclosing a text in the quotes. We can use both single
as well asdouble quotes for a String.
Eg:
"Aman" , '12345'
Types of Strings:
a).Single line String- Strings that are terminated within a single line are known as
Single lineStrings.
Eg:
1. >>> text1='hello'
b).Multi line String- A piece of text that is spread along multiple lines is known as
Multiple lineString.
of each line.Eg:
1. >>> text1='hello\
2. user'
3. >>> text1
4. 'hellouse
r'5. >>>
28
PREPARED BY P. SATHISH(PhD)
Eg:
1. >>> str2='''''welcome
2. to
3. SSSIT'''
4. >>> print str2
5. welcome
6. to
7. SSSIT
8. >>>
Numeric Literals are immutable. Numeric literals can belong to following four different
numerical types.
A Boolean literal can have any of the two values: True or False.
None is used to specify to that field that is not created. It is also used for end of lists in
Python.Eg:
1. >>> val1=10
2. >>> val2=None
29
PREPARED BY P. SATHISH(PhD)
3. >>> val1
4. 10
5. >>> val2
6. >>> print val2
7. None
8. >>>
V.Literal Collections.
List:
o List contain items of different data types. Lists are mutable i.e., modifiable.
o The values stored in List are separated by commas(,) and enclosed within
a squarebrackets([]). We can store different type of data in a List.
o Value stored in a List can be retrieved using the slice operator([] and [:]).
o The plus sign (+) is the list concatenation and asterisk(*) is the repetition operator.
Eg:
1. >>> list=['aman',678,20.4,'saurav']
2. >>> list1=[456,'rahul']
3. >>> list
4. ['aman', 678, 20.4, 'saurav']
5. >>> list[1:3]
6. [678, 20.4]
7. >>> list+list1
8. ['aman', 678, 20.4, 'saurav', 456, 'rahul']
9. >>> list1*2
10. [456, 'rahul', 456, 'rahul']
11. >>>
30
PREPARED BY P. SATHISH(PhD)
Python Operators
Operators are particular symbols that are used to perform operations on operands. It
returnsresult that can be used in application.
Example
1. 4 + 5 = 9
Here 4 and 5 are Operands and (+) , (=) signs are the operators. This expression
produces theoutput 9.
Types of Operators
1. Arithmetic Operators.
2. Relational Operators.
3. Assignment Operators.
4. Logical Operators.
5. Membership Operators.
6. Identity Operators.
7. Bitwise Operators.
Arithmetic Operators
The following table contains the arithmetic operators that are used to perform
arithmeticoperations.
Operators Description
+ To perform addition
31
PREPARED BY P. SATHISH(PhD)
- To perform subtraction
* To perform multiplication
/ To perform division
Example
1. >>> 10+20
2. 30
3. >>> 20-10
4. 10
5. >>> 10*2
6. 20
7. >>> 10/2
8. 5
9. >>> 10%3
10. 1
11. >>> 2**3
12. 8
13. >>> 10//3
14. 3
15. >>>
32
PREPARED BY P. SATHISH(PhD)
Relational Operators
The following table contains the relational operators that are used to check relations.
Operators Description
== Equal to
!= Not equal to
eg:
1. >>> 10<20
2. True
3. >>> 10>20
4. False
5. >>> 10<=10
6. True
7. >>> 20>=15
8. True
9. >>> 5==6
10. False
33
PREPARED BY P. SATHISH(PhD)
Assignment Operators
The following table contains the assignment operators that are used to assign values to
thevariables.
Operators Description
= Assignment
Example
1. >>> c=10
2. >>> c
34
PREPARED BY P. SATHISH(PhD)
3. 10
4. >>> c+=5
5. >>> c
6. 15
7. >>> c-=5
8. >>> c
9. 10
10. >>> c*=2
11. >>> c
12. 20
13. >>> c/=2
14. >>> c
15. 10
16. >>> c%=3
17. >>> c
18. 1
19. >>> c=5
20. >>> c**=2
21. >>> c
22. 25
23. >>> c//=2
24. >>> c
25. 12
26. >>>
Logical Operators
The following table contains the arithmetic operators that are used to perform
arithmeticoperations.
Operators Description
and Logical AND(When both conditions are true output will be true)
35
PREPARED BY P. SATHISH(PhD)
Example
Output:
1. >>>
2. True
3. True
4. False
5. >>>
Membership Operators
Operators Description
not in Returns true if a variable is not in sequence of another variable, else false.
Example
1. a=10
2. b=20
3. list=[10,20,30,40,50];
36
PREPARED BY P. SATHISH(PhD)
4. if (a in list):
5. print "a is in given list"
6. else:
7. print "a is not in given list"
8. if(b not in list):
9. print "b is not given in list"
10. else:
11. print "b is given in list"
Output:
1. >>>
2. a is in given list
3. b is given in
list4. >>>
Identity Operators
Operators Description
is not Returns true if identity of two operands are not same, else false.
Example
1. a=20
2. b=20
3. if( a is b):
4. print a,b have same identity
5. else:
6. print a, b are different
37
By PS
7. b=10
8. if( a is not b):
9. print a,b have different identity
10. else:
11. print a,b have same identity
Output
1. >>>
2. a,b have same identity
3. a,b have
different identity4.
>>>
Python Comments
In case user wants to specify a single line comment, then comment must start with ?#?
Eg:
eg:
1. ''''' This
2. Is
3. Multipline comment'''
eg:
1|P ag e
python list
By PS
Python List
A list in Python is used to store the sequence of various types of data. Python
lists are mutable type its mean we can modify its element after it created. However,
Python consists of six data-types that are capable to store the sequences, but the most
common and reliable type is the list.
IIf we try to print the type of L1, L2, and L3 using type() function then it will come out
to be alist.
1. print(type(L1))
2. print(type(L2))
Output:
<class 'list'>
<class 'list'>
Characteristics of Lists
2|P ag e
python list
By PS
3|P ag e
python list
By PS
Let's check the first statement that lists are the ordered.
1. a = [1,2,"Peter",4.50,"Ricky",5,6]
2. b = [1,2,5,"Peter",4.50,"Ricky",6]
3. a ==b
Output:
False
Both lists have consisted of the same elements, but the second list changed the
index position of the 5th element that violates the order of lists. When compare both
lists it returns the false.
Lists maintain the order of the element for the lifetime. That's why it is the
ordered collection of objects.
Output:
True
4|P ag e
python list
By PS
Output:
5|P ag e
python list
By PS
In the above example, we have created the lists which consist of the employee
and department details and printed the corresponding details. Observe the above code
to understand the concept of the list better.
The indexing is processed in the same way as it happens with the strings. The
elementsof the list can be accessed by using the slice operator [].
The index starts from 0 and goes to length - 1. The first element of the list is
stored atthe 0th index, the second element of the list is stored at the 1st index, and so
on.
6|P ag e
python list
By PS
We can get the sub-list of the list using the following syntax.
1. list_varible(start:stop:step)
1. list = [1,2,3,4,5,6,7]
2. print(list[0])
3. print(list[1])
4. print(list[2])
5. print(list[3])
6. # Slicing the elements
7. print(list[0:6])
8. # By default the index value is 0 so its starts from the 0th element and go for index -1.
9. print(list[:])
10. print(list[2:5])
11. print(list[1:6:2])
Output:
1
2
3
4
[1, 2, 3, 4, 5, 6]
[1, 2, 3, 4, 5, 6, 7]
[3, 4, 5]
[2, 4, 6]
7|P ag e
python list
By PS
Unlike other languages, Python provides the flexibility to use the negative
indexing also. The negative indices are counted from the right. The last element
(rightmost) of the list has the index -1; its adjacent left element is present at the index -2
and so on until the left-most elements are encountered.
Let's have a look at the following example where we will use negative indexing to
accessthe elements of the list.
1. list = [1,2,3,4,5]
2. print(list[-1])
3. print(list[-3:])
4. print(list[:-1])
5. print(list[-3:-1])
Output:
5
[3, 4, 5]
[1, 2, 3, 4]
[3, 4]
8|P ag e
python list
By PS
Lists are the most versatile data structures in Python since they are mutable,
and theirvalues can be updated by using the slice and assignment operator.
Python also provides append() and insert() methods, which can be used to add
values tothe list.
Consider the following example to update the values inside the list.
1. list = [1, 2, 3, 4, 5, 6]
2. print(list)
3. # It will assign value to the value to the second
index4. list[2] = 10
5. print(list)
6. # Adding multiple-
element7. list[1:3] = [89, 78]
8. print(list)
9. # It will add value at the end of the
list10. list[-1] = 25
11. print(list)
Output:
[1, 2, 3, 4, 5, 6]
[1, 2, 10, 4, 5, 6]
[1, 89, 78, 4, 5, 6]
[1, 89, 78, 4, 5, 25]
9|P ag e
python list
By PS
The list elements can also be deleted by using the del keyword. Python also
provides usthe remove() method if we do not know which element is to be deleted from
the list.
1. list = [1, 2, 3, 4, 5, 6]
2. print(list)
3. # It will assign value to the value to second
index4. list[2] = 10
5. print(list)
6. # Adding multiple
element7. list[1:3] = [89, 78]
8. print(list)
9. # It will add value at the end of the
list10. list[-1] = 25
11. print(list)
Output:
[1, 2, 3, 4, 5, 6]
[1, 2, 10, 4, 5, 6]
[1, 89, 78, 4, 5, 6]
[1, 89, 78, 4, 5, 25]
The concatenation (+) and repetition (*) operators work in the same way as they were
workingwith the strings.
10 | P a g e
python list
By PS
11 | P a g e
python list
By PS
Membership It returns true if a particular item exists in a print(2 in l1) prints True.
particular list otherwise false.
Iteration The for loop is used to iterate over the list for i in
elements. l1:
print(i)
Output
1
2
3
4
Length It is used to get the length of the list len(l1) = 4
Iterating a List
A list can be iterated by using a for - in loop. A simple list containing four strings, which
can beiterated as follows.
12 | P a g e
python list
By PS
Output:
John
David
James
Jonatha
Python provides append() function which is used to add an element to the list.
However,the append() function can only add value to the end of the list.
Consider the following example in which, we are taking the elements of the list
from theuser and printing the list on the console.
13 | P a g e
python list
By PS
11. for i in l:
12. print(i, end = " ")
Output:
Python provides the remove() function which is used to remove the element
from thelist. Consider the following example to understand this concept.
Example -
1. list = [0,1,2,3,4]
2. print("printing original list: ");
3. for i in list:
4. print(i,end=" ")
5. list.remove(2)
6. print("\nprinting the list after the removal of first element...")
7. for i in list:
8. print(i,end=" ")
14 | P a g e
python list
By PS
Output:
Python provides the following built-in functions, which can be used with the lists.
1 cmp(list1, It compares the elements This method is not used in the Python 3
list2) of both the lists. and the above versions.
15 | P a g e
python list
By PS
16 | P a g e
python list
By PS
Example: 1- Write the program to remove the duplicate element of the list.
1. list1 = [1,2,2,3,55,98,65,65,13,29]
2. # Declare an empty list that will store unique values
3. list2 = []
4. for i in list1:
5. if i not in list2:
6. list2.append(i)
7. print(list2)
Output:
Example:2- Write a program to find the sum of the element in the list.
1. list1 = [3,4,5,9,10,12,24]
2. sum = 0
3. for i in list1:
4. sum = sum+i
5. print("The sum is:",sum)
Output:
17 | P a g e
python list
By ps
Example: 3- Write the program to find the lists consist of at least one common element.
1. list1 = [1,2,3,4,5,6]
2. list2 = [7,8,9,2,10]
3. for x in list1:
4. for y in list2:
5. if x == y:
6. print("The common element is:",x)
Output:
1|P age
By PS(PhD)
By ps
Python Tuple
Python Tuple is used to store the sequence of immutable Python objects. The
tuple is similar to lists since the value of the items stored in the list can be changed,
whereas the tupleis immutable, and the value of the items stored in the tuple cannot be
changed.
Creating a tuple
Output:
<class 'tuple'>
<class 'tuple'>
<class 'tuple'>
Note: The tuple which is created without using parentheses is also known as tuple packing.
T4 = ()
2|P age
By PS(PhD)
By ps
Creating a tuple with single element is slightly different. We will need to put
commaafter the element to declare the tuple.
1. tup1 = ("Gvkinfotech")
2. print(type(tup1))
3. #Creating a tuple with single element
4. tup2 = ("Gvkinfotech",)
5. print(type(tup2))
Output:
<class 'str'>
<class 'tuple'>
A tuple is indexed in the same way as the lists. The items in the tuple can be
accessed byusing their specific index value.
Example - 1
1. tuple1 = (10, 20, 30, 40, 50, 60)
2. print(tuple1)
3. count = 0
4. for i in tuple1:
5. print("tuple1[%d] = %d"%(count, i))
6. count = count+1
Output:
3|P age
By PS(PhD)
By ps
tuple1[2] = 30
tuple1[3] = 40
tuple1[4] = 50
tuple1[5] = 60
Example - 2
1. tuple1 = tuple(input("Enter the tuple elements ..."))
2. print(tuple1)
3. count = 0
4. for i in tuple1:
5. print("tuple1[%d] = %s"%(count, i))
6. count = count+1
Output:
A tuple is indexed in the same way as the lists. The items in the tuple can be
accessed byusing their specific index value.
The indexing and slicing in the tuple are similar to lists. The indexing in the tuple
startsfrom 0 and goes to length(tuple) - 1.
4|P age
By PS(PhD)
By ps
The items in the tuple can be accessed by using the index [] operator. Python also
allowsus to use the colon operator to access multiple items in the tuple.
Consider the following image to understand the indexing and slicing in detail.
1. tup = (1,2,3,4,5,6,7)
2. print(tup[0])
3. print(tup[1])
4. print(tup[2])
5. # It will give the IndexError
6. print(tup[8])
5|P age
By PS(PhD)
By ps
Output:
1
2
3
tuple index out of range
In the above code, the tuple has 7 elements which denote 0 to 6. We tried to
access anelement outside of tuple that raised an IndexError.
1. tuple = (1,2,3,4,5,6,7)
2. #element 1 to end
3. print(tuple[1:])
4. #element 0 to 3 element
5. print(tuple[:4])
6. #element 1 to 4 element
7. print(tuple[1:5])
8. # element 0 to 6 and take step of 2
9. print(tuple[0:6:2])
Output:
(2, 3, 4, 5, 6, 7)
(1, 2, 3, 4)
(1, 2, 3, 4)
(1, 3, 5)
Negative Indexing
The tuple element can also access by using negative indexing. The index of -1
denotesthe rightmost element and -2 to the second last item and so on.
6|P age
By PS(PhD)
By ps
The elements from left to right are traversed using the negative indexing.
Output:
5
2
(3, 4)
(1, 2, 3, 4)
(4, 5)
Deleting Tuple
Unlike lists, the tuple items cannot be deleted by using the del keyword as tuples
areimmutable. To delete an entire tuple, we can use the del keyword with the tuple
name.
1. tuple1 = (1, 2, 3, 4, 5, 6)
2. print(tuple1)
3. del tuple1[0]
4. print(tuple1)
5. del tuple1
6. print(tuple1)
7|P age
By PS(PhD)
By ps
8|P age
By PS(PhD)
By ps
Output:
(1, 2, 3, 4, 5, 6)
Traceback (most recent call
last): File "tuple.py", line 4, in
<module>print(tuple1)
NameError: name 'tuple1' is not defined
The operators like concatenation (+), repetition (*), Membership (in) works in the
sameway as they work with the list. Consider the following table for more detail.
Membership It returns true if a particular item exists in the tuple print (2 in T1) prints
otherwise false True.
Iteration The for loop is used to iterate over the tuple for i in
elements. T1:
print(i)
Output
1
2
3
9|P age
By PS(PhD)
By ps
4
5
SN Function Descriptio
n
1 cmp(tuple It compares two tuples and returns true if tuple1 is greater than
1,tuple2) tuple2otherwise false.
1. Using tuple instead of list gives us a clear idea that tuple data is constant and
must not bechanged.
2. Tuple can simulate a dictionary without keys. Consider the following nested
structure,which can be used as a dictionary.
10 | P a g
By PS(PhD)
By PS (PhD)
SN Lis Tupl
t e
1 The literal syntax of list is shown by The literal syntax of the tuple is shown by the
().
the[].
3 The List has the a variable length. The tuple has the fixed length.
4 The list provides more functionality The tuple provides less functionality than
thana tuple. thelist.
5 The list is used in the scenario in The tuple is used in the cases where we
which we need to store the simple need tostore the read-only collections i.e.,
collections with no constraints the value of the items cannot be changed. It
where the value of the items can be can be used as the key inside the
changed. dictionary.
6 The lists are less memory efficient The tuples are more memory efficient
than atuple. becauseof its immutability.
1
By PS (PhD)
Python Set
A Python set is the collection of the unordered items. Each element in the set
must be unique, immutable, and the sets remove the duplicate elements. Sets are
mutable which meanswe can modify it after its creation.
Creating a set
Output:
2
By PS (PhD)
Monday
Saturday
Thursday
Sunday
Wednesda
y
Example 2: Using set() method
1. Days = set(["Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"])
2. print(Days)
3. print(type(Days))
4. print("looping through the set elements ... ")
5. for i in Days:
6. print(i)
Output:
It can contain any type of element such as integer, float, tuple etc. But mutable
elements (list, dictionary, set) can't be a member of set.
3
By PS (PhD)
Output:
<class 'set'>
Creating an empty set is a bit different because empty curly {} braces are also
used to create a dictionary as well. So Python provides the set() method used without an
argument tocreate an empty set.
4
By PS (PhD)
3. print(type(set3))
4.
5. # Empty set using set() function
6. set4 = set()
7. print(type(set4)
)Output:
<class 'dict'>
<class 'set'>
Let's see what happened if we provide the duplicate element to the set.
1. set5 = {1,2,4,4,5,8,9,9,10}
2. print("Return set with unique elements:",set5)
Output:
In the above code, we can see that set5 consisted of multiple duplicate elements
whenwe printed it remove the duplicity from the set.
Python provides the add() method and update() method which can be used to
add some particular item to the set. The add() method is used to add a single element
whereas theupdate() method is used to add multiple elements to the set. Consider the
following example.
5
By PS (PhD)
6
By PS (PhD)
Output:
7
By PS (PhD)
To add more than one item in the set, Python provides the update() method. It
acceptsiterable as an argument.
;Output:
Python provides the discard() method and remove() method which can be used to
remove the items from the set. The difference between these function, using discard()
function if the item does not exist in the set then the set remain unchanged whereas
remove() method will throughan error.
8
By PS (PhD)
Output:
9
By PS (PhD)
Python provides also the remove() method to remove the item from the set.
Considerthe following example to remove the items using remove() method.
s)Output:
We can also use the pop() method to remove the item. Generally, the pop()
method will always remove the last item but the set is unordered, we can't determine
which element will bepopped from set.
Consider the following example to remove the item from the set using pop() method.
10
By PS (PhD)
3. print(Months)
4. print("\nRemoving some months from the set...");
5. Months.pop();
6. Months.pop();
7. print("\nPrinting the modified set...");
8. print(Months)
Output:
set...
Python provides the clear() method to remove all the items from the set.
11
By PS (PhD)
Output:
Despite the fact that discard() and remove() method both perform the same task,
Thereis one main difference between discard() and remove().
If the key to be deleted from the set using discard() doesn't exist in the set, the
Pythonwill not give the error. The program maintains its control flow.
On the other hand, if the item to be deleted from the set using remove() doesn't
exist inthe set, the Python will raise an error.
Example-
1. Months = set(["January","February", "March", "April", "May", "June"])
2. print("\nprinting the original set ... ")
3. print(Months)
4. print("\nRemoving items through discard() method...");
5. Months.discard("Feb"); #will not give an error although the key feb is not available in the set
6. print("\nprinting the modified set...")
7. print(Months)
8. print("\nRemoving items through remove() method...");
12
By PS (PhD)
9. Months.remove("Jan") #will give an error as the key jan is not available in the set.
10. print("\nPrinting the modified set...")
11. print(Months)
Output:
The union of two sets is calculated by using the pipe (|) operator. The union of the
twosets contains all the items that are present in both the sets.
13
By PS (PhD)
Output:
Python also provides the union() method which can also be used to calculate the union
of twosets. Consider the following example.
1. Days1 = {"Monday","Tuesday","Wednesday","Thursday"}
2. Days2 = {"Friday","Saturday","Sunday"}
3. print(Days1.union(Days2)) #printing the union of the sets
14
By PS (PhD)
Output:
The intersection of two sets can be performed by the and & operator
orthe intersection() function. The intersection of the two sets is given as the set of the
elements that common in both sets.
Output:
{'Monday', 'Tuesday'}
15
By PS (PhD)
Output:
{'Martin', 'David'}
Example 3:
1. set1 = {1,2,3,4,5,6,7}
2. set2 = {1,2,20,32,5,9}
3. set3 = set1.intersection(set2)
4. print(set3)
Output:
{1,2,5}
The intersection_update() method removes the items from the original set that
are notpresent in both the sets (all the sets if more than one are specified).
16
By PS (PhD)
Output:
{'castle'}
The difference of two sets can be calculated by using the subtraction (-)
operator or intersection() method. Suppose there are two sets A and B, and the
difference is A-B that denotes the resulting set will be obtained that element of A, which
is not present in the set B.
17
By PS (PhD)
Output:
{'Thursday', 'Wednesday'}
Output:
{'Thursday', 'Wednesday'}
18
By PS (PhD)
1. a = {1,2,3,4,5,6}
2. b = {1,2,9,8,10}
3. c = a^b
4. print(c)
Output:
{3, 4, 5, 6, 8, 9, 10}
1. a = {1,2,3,4,5,6}
2. b = {1,2,9,8,10}
3. c = a.symmetric_difference(b)
4. print(c)
Output:
{3, 4, 5, 6, 8, 9, 10}
19
By PS (PhD)
Set comparisons
Python allows us to use the comparison operators i.e., <, >, <=, >= , == with the
sets byusing which we can check whether a set is a subset, superset, or equivalent to
other set. The boolean true or false is returned depending upon the items present inside
the sets.
Output:
Tru
e
Fals
FrozenSets
The frozen sets are the immutable form of the normal sets, i.e., the items of the
frozenset cannot be changed and therefore it can be used as a key in the dictionary.
20
By PS (PhD)
The elements of the frozen set cannot be changed after the creation. We cannot
changeor append the content of the frozen sets by using the methods like add() or
remove().
The frozenset() method is used to create the frozenset object. The iterable
sequence ispassed into this method which is converted into the frozen set as a return
type of the method.
1. Frozenset = frozenset([1,2,3,4,5])
2. print(type(Frozenset))
3. print("\nprinting the content of frozen set...")
4. for i in Frozenset:
5. print(i);
6. Frozenset.add(6) #gives an error since we cannot change the content of Frozenset
after creation
Output:
21
By PS (PhD)
<class 'frozenset'>
22
By PS (PhD)
If we pass the dictionary as the sequence inside the frozenset() method, it will
take onlythe keys from the dictionary and returns a frozenset that contains the key of
the dictionary as its elements.
Output:
<class 'dict'>
<class
'frozenset'>
Name
Countr
yID
Set Programming Example
Example - 1: Write a program to remove the given number from the set.
1. my_set = {1,2,3,4,5,6,12,24}
2. n = int(input("Enter the number you want to remove"))
3. my_set.discard(n)
4. print("After Removing:",my_set)
23
By PS (PhD)
Output:
1. set1 = set([1,2,4,"John","CS"])
2. set1.update(["Apple","Mango","Grapes"])
3. print(set1)
Output:
Output:
1. set1 =
{23,44,56,67,90,45,"Gvkinfotech"}2. set2
= {13,23,56,76,"Sachin"}
3. set3 = set1.intersection(set2)
4. print(set3)
24
By PS (PhD)
25
By PS (PhD)
Output:
{56, 23}
1. set1 =
{23,44,56,67,90,45,"Gvkinfotech"}2. set2
= {13,23,56,76,"Sachin"}
3. set3 = set1.intersection(set2)
4. print(set3)
Output:
Above code raised an error because frozensets are immutable and can't be
changed aftercreation.
Example - 6: Write the program to find the issuperset, issubset and superset.
1. set1 = set(["Peter","James","Camroon","Ricky","Donald"])
2. set2 = set(["Camroon","Washington","Peter"])
3. set3 =
set(["Peter"])4.
5. issubset = set1 >= set2
6. print(issubset)
7. issuperset = set1 <= set2
8. print(issuperset)
9. issubset = set3 <= set2
10. print(issubset)
11. issuperset = set2 >= set3
12. print(issuperset)
26
By PS (PhD)
Output:
Fals
e
Fals
e
T
Python Built-in set methods
27
By PS (PhD)
28
By PS (PhD)
29