0% found this document useful (0 votes)
31 views

Python I Unit Notes

Python unit 1 notes for b.tech students

Uploaded by

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

Python I Unit Notes

Python unit 1 notes for b.tech students

Uploaded by

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

PREPARED BY P.

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

Python provides lots of features that are listed below.

1) Easy to Learn and Use

Python is easy to learn and use. It is developer-friendly and high level


programminglanguage.

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.

5) Free and Open Source

Python language is freely available at offical web address.The source-code is


alsoavailable. Therefore it is open source.

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.

8) Large Standard Library

Python has a large and broad library and provides rich set of module and
functions forrapid application development.

9) GUI Programming Support

Graphical user interfaces can be developed using Python.

10) Integrated

It can be easily integrated with languages like C, C++, JAVA etc.

Python History

 Python laid its foundation in the late 1980s.


 The implementation of Python was started in the December 1989 by
Guido VanRossum at CWI in Netherland.
 In February 1991, van Rossum published the code (labeled version 0.9.0) to alt.sources.
 In 1994, Python 1.0 was released with new features like: lambda, map, filter, and reduce.
 Python 2.0 added new features like: list comprehensions, garbage collection system.

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.

Python Released Date


Version

Python January 1994


1.0

Python December 31, 1997


1.5

Python September 5, 2000


1.6

Python October 16, 2000


2.0

Python April 17, 2001


2.1

Python December 21, 2001


2.2

Python July 29, 2003


2.3

Python November 30, 2004


2.4

4
PREPARED BY P. SATHISH(PhD)

Python September 19, 2006


2.5

Python October 1, 2008


2.6

5
PREPARED BY P. SATHISH(PhD)

Python 2.7 July 3, 2010

Python 3.0 December 3, 2008

Python 3.1 June 27, 2009

Python 3.2 February 20, 2011

Python 3.3 September 29, 2012

Python 3.4 March 16, 2014

Python 3.5 September 13, 2015

Python 3.6 December 23, 2016

Python 3.6.4 December 19, 2017

Python Applications Area

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.

Here, we are specifing applications areas where python can be applied.

1) Web Applications

We can use Python to develop web applications. It provides libraries to handle


internet protocols such as HTML and XML, JSON, Email processing, request,
beautifulSoup, Feedparseretc. It also provides Frameworks such as Django, Pyramid,
Flask etc to design and devlelop webbased applications. Some important
developments are: PythonWikiEngines, Pocoo, PythonBlogSoftware etc.

2) Desktop GUI Applications

Python provides Tk GUI library to develop user interface in python based


application.Some other useful toolkits wxWidgets, Kivy, pyqt that are useable on several
platforms. The Kivy is popular for writing multitouch applications.

6
PREPARED BY P. SATHISH(PhD)

3) Software Development

Python is helpful for software development process. It works as a support


language andcan be used for build control and management, testing etc.

4) Scientific and Numeric

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

Python is used to build Bussiness applications like ERP and e-commerce


systems. Trytonis a high level application platform.

6) Console Based Application

We can use Python to develop console based applications. For example: IPython.

7) Audio or Video based Applications

Python is awesome to perform multiple tasks and can be used to develop


multimediaapplications. Some of real applications are: TimPlayer, cplay etc.

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.

10) Applications for Images

Using Python several application can be developed for image. Applications


developedare: VPython, Gogh, imgSeek etc.

There are several such applications which can be developed using Python

7
PREPARED BY P. SATHISH(PhD)

HOW TO INSTALL PYTHON

--->To start with Python, first make sure that the Python is installed on local computer.

For Windows operating system, the installation process is given below.

1. To install Python, firstly download the Python distribution from www.python.org/download.

2. After downloading the Python distribution, double click on the downloaded


software toexecute it. Follow the following installtion steps.

8
PREPARED BY P. SATHISH(PhD)

9
PREPARED BY P. SATHISH(PhD)

Click the Finish button and Python will be installed on your system.

SETTING PATH IN PYTHON

Before starting working with Python, a specific path is to set.

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:

Right click on My Computer ->Properties ->Advanced System setting ->Environment Variable -


>New

In Variable name write path and in Variable value copy path up to C://Python(i.e., path
wherePython is installed). Click Ok ->Ok.

Path will be set for executing Python programs.

1. Right click on My Computer and click on properties.

2. Click on Advanced System settings

10
PREPARED BY P. SATHISH(PhD)

3. Click on Environment Variable tab.

4. Click on new tab of user variables.

11
PREPARED BY P. SATHISH(PhD)

5. Write path in variable name

6. Copy the path of Python folder

12
PREPARED BY P. SATHISH(PhD)

7. Paste path of Python in variable value.

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. print("hello world by python!")

Execute this example by using following command.

1. Python3 hello.py

After executing, it produces the following output to the screen.

Output

hello world by python!

Python Example using Interactive Shell

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".

A simple python example is given below.

1. >>> a="Welcome To Python"


2. >>> print a
3. Welcome To
Python4. >>>

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.

Python 3.4 Example

In python 3.4 version, you need to add parenthesis () in a string code to print it.

1. >>> a=("Welcome To Python Example")


2. >>> print a
3. Welcome To Python
Example4. >>>

How to execute python

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)

Now we can execute our Python

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)

Save it by .py extension.

Now open Command prompt and execute it by

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.

3) Using IDE (Integrated Development Environment)

We can execute our Python code using a Graphical User Interface

(GUI).All you need to do is:

Click on Start button -> All Programs -> Python -> IDLE(Python GUI)

19
PREPARED BY P. SATHISH(PhD)

We can use both Interactive as well as Script mode in IDE.

1) Using Interactive mode:

Execute our Python code on the Python prompt and it will display result simultaneously.

2) Using Script Mode:

i) Click on Start button -> All Programs -> Python -> IDLE(Python GUI)

ii) Python Shell will be opened. Now click on File -> New Window.

A new Editor will be opened. Write our Python code here.

20
PREPARED BY P. SATHISH(PhD)

Click on file -> save as

Run code by clicking on Run in the Menu bar.

21
PREPARED BY P. SATHISH(PhD)

Run -> Run Module

Result will be displayed on a new Python shell as:

22
PREPARED BY P. SATHISH(PhD)

Python Variables

 Variable is a name which is used to refer memory location. Variable also


known asidentifier and used to hold value.
 In Python, we don't need to specify the type of variable because Python is a
type inferlanguage and smart enough to get variable type.
 Variable names can be a group of both letters and digits, but they have to
begin with aletter or an underscore.
 It is recomended to use lowercase letters for variable name. Rahul and rahul
both are twodifferent variables.

Note - Variable name should not be a keyword.

Declaring Variable and Assigning Values

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.

The equal (=) operator is used to assign value to a variable.

23
PREPARED BY P. SATHISH(PhD)

Output:

1. >>>
2. 10
3. ravi
4. 20000.67
5. >>>

Multiple Assignment

Python allows us to assign a value to multiple variables in a single statement


which isalso known as multiple assignment.

We can apply multiple assignments in two ways either by assigning a single


value to multiple variables or assigning multiple values to multiple variables. Lets see
given examples.

1. Assigning single value to multiple

variablesEg:

1. x=y=z=50
2. print iple
3. print y
4. print z

Output:

1. >>>
2. 50
3. 50
4. 50
5. >>>

2.Assigning multiple values to multiple

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

The values will be assigned in the order in which variables

appears.Basic Fundamentals:

This section contains the basic fundamentals of Python like :

i) Tokens and their types.

ii) Comment

sa)Tokens:

o Tokens can be defined as a punctuator mark, reserved words and each


individual word ina statement.
o Token is the smallest unit inside the given program.

There are following tokens in Python:

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.

True False None and as

asset def class continue break

else finally elif del except

global for if from import

raise try or return pass

nonlocal in not is lambda

Identifiers

Identifiers are the names given to the fundamental building blocks in a program.

These can be variables ,class ,object ,functions , lists , dictionaries etc.

There are certain rules defined for naming i.e., Identifiers.

I. An identifier is a long sequence of characters and numbers.

II. No special character except underscore ( _ ) can be used as an

identifier.III.Keyword should not be used as an identifier name.

IV. Python is case sensitive. So using case is significant.

V. First character of an identifier can be character, underscore ( _ ) but not digit.

27
PREPARED BY P. SATHISH(PhD)

Python Literals

Literals can be defined as a data that is given in a variable or

constant.Python support the following 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:

There are two types of Strings supported in Python:

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.

There are two ways to create Multiline

Strings: 1). Adding black slash at the end

of each line.Eg:

1. >>> text1='hello\
2. user'
3. >>> text1
4. 'hellouse
r'5. >>>

2).Using triple quotation marks:-

28
PREPARED BY P. SATHISH(PhD)

Eg:

1. >>> str2='''''welcome
2. to
3. SSSIT'''
4. >>> print str2
5. welcome
6. to
7. SSSIT
8. >>>

II. Numeric literals:

Numeric Literals are immutable. Numeric literals can belong to following four different
numerical types.

Int(signe Long(long integers) float(floatin Complex(complex)


d gpoint)
integers)

Numbers( can Integers of Real numbers In the form of a+bj where


be both positive unlimited size with both aforms the real part and
and negative) followed by integerand b forms the imaginary
with no lowercase or fractional part part ofcomplex number.
fractional uppercase L eg: -26.2 eg: 3.14j
part.eg:100 eg:87032845L

III. Boolean literals:

A Boolean literal can have any of the two values: True or False.

IV. Special literals.

Python contains one special literal i.e., None.

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.

Collections such as tuples, lists and Dictionary are used in Python.

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

Python supports the following 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

// Perform Floor division(gives integer value after division)

+ To perform addition

31
PREPARED BY P. SATHISH(PhD)

- To perform subtraction

* To perform multiplication

/ To perform division

% To return remainder after division(Modulus)

** Perform exponent(raise to power)

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

< Less than

> Greater than

<= Less than or equal to

>= Greater than or equal to

== Equal to

!= Not equal to

<> Not equal to(similar 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)

11. >>> 5!=6


12. True
13. >>> 10<>2
14.
True15.
>>>

Assignment Operators

The following table contains the assignment operators that are used to assign values to
thevariables.

Operators Description

= Assignment

/= Divide and Assign

+= Add and assign

-= Subtract and Assign

*= Multiply and assign

%= Modulus and assign

**= Exponent and assign

//= Floor division and assign

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)

or Logical OR (If any one condition is true output will be true)

35
PREPARED BY P. SATHISH(PhD)

not Logical NOT(Compliment the condition i.e., reverse)

Example

1. a=5>4 and 3>2


2. print a
3. b=5>4 or 3<2
4. print b
5. c=not(5>4)
6. print c

Output:

1. >>>
2. True
3. True
4. False
5. >>>

Membership Operators

The following table contains the membership operators.

Operators Description

in Returns true if a variable is in sequence of another variable, else false.

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

The following table contains the identity operators.

Operators Description

is Returns true if identity of two operands are same, else false

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

Python supports two types of comments:

1) Single lined comment:

In case user wants to specify a single line comment, then comment must start with ?#?

Eg:

1. # This is single line comment.

2) Multi lined Comment:

Multi lined comment can be given inside triple quotes.

eg:

1. ''''' This
2. Is
3. Multipline comment'''

eg:

1. #single line comment


2. print "Hello Python"
3. '''''This is
4. multiline comment'''

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.

A list can be defined as a collection of values or items of different types. The


items in thelist are separated with the comma (,) and enclosed with the square brackets
[].

A list can be define as below

1. L1 = ["John", 102, "USA"]


2. L2 = [1, 2, 3, 4, 5, 6]

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

The list has the following characteristics:

 The lists are ordered.


 The element of the list can access by index.

2|P ag e
python list
By PS

3|P ag e
python list
By PS

 The lists are the mutable type.


 The lists are mutable types.
 A list can store the number of various elements.

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.

1. a = [1, 2,"Peter", 4.50,"Ricky",5, 6]


2. b = [1, 2,"Peter", 4.50,"Ricky",5, 6]
3. a == b

Output:

True

4|P ag e
python list
By PS

Let's have a look at the list example in detail.

1. emp = ["John", 102, "USA"]


2. Dep1 = ["CS",10]
3. Dep2 = ["IT",11]
4. HOD_CS = [10,"Mr. Holding"]
5. HOD_IT = [11, "Mr. Bewon"]
6. print("printing employee data...")
7. print("Name : %s, ID: %d, Country: %s"%(emp[0],emp[1],emp[2]))
8. print("printing departments...")
9. print("Department 1:\nName: %s, ID: %d\nDepartment 2:\nName: %s, ID:
%s"%(Dep1[0],Dep2[1],Dep2[0],Dep2[1]))
10. print("HOD Details ")
11. print("CS HOD Name: %s, Id: %d"%(HOD_CS[1],HOD_CS[0]))
12. print("IT HOD Name: %s, Id: %d"%(HOD_IT[1],HOD_IT[0]))
13. print(type(emp),type(Dep1),type(Dep2),type(HOD_CS),type(HOD_IT))

Output:

printing employee data...


Name : John, ID: 102, Country:
USAprinting departments...
Department 1:
Name: CS, ID: 11
Department 2:
Name: IT, ID: 11
HOD Details ....
CS HOD Name: Mr. Holding, Id:
10IT HOD Name: Mr. Bewon,
Id: 11
<class 'list'> <class 'list'> <class 'list'> <class 'list'> <class 'list'>

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.

List indexing and splitting

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)

 The start denotes the starting index position of the list.


 The stop denotes the last index position of the list.
 The step is used to skip the nth element within a start:stop

Consider the following example:

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

As we discussed above, we can get an element by using negative indexing. In the


above code, the first print statement returned the rightmost element of the list. The
second print statement returned the sub-list, and so on.

Updating List values

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.

Consider the following example to delete the list elements.

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]

Python List Operations

The concatenation (+) and repetition (*) operators work in the same way as they were
workingwith the strings.

Let's see how the list responds to various operators.

10 | P a g e
python list
By PS

11 | P a g e
python list
By PS

1. Consider a Lists l1 = [1, 2, 3, 4], and l2 = [5, 6, 7, 8] to perform operation.

Operator Descriptio Exampl


n e

Repetition The repetition operator enables the list l1*2 = [1, 2, 3, 4, 1, 2, 3, 4]


elementsto be repeated multiple times.

Concatenation It concatenates the list mentioned on either l1+l2 = [1, 2, 3, 4, 5, 6, 7, 8]


sideof the operator.

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

1. list = ["John", "David", "James", "Jonathan"]


2. for i in list:
3. # The i variable will iterate over the elements of the List and contains each element in
each iteration.
4. print(i)

Output:

John
David
James
Jonatha

Adding elements to the list

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.

1. #Declaring the empty


list2. l =[]
3. #Number of elements will be entered by the user
4. n = int(input("Enter the number of elements in the list:"))
5. # for loop to take the input
6. for i in range(0,n):
7. # The input is taken from the user and added to the list as the item
8. l.append(input("Enter the item:"))
9. print("printing the list items..")
10. # traversal loop to print the list items

13 | P a g e
python list
By PS

11. for i in l:
12. print(i, end = " ")

Output:

Enter the number of elements in the


list:5Enter the item:25
Enter the item:46
Enter the item:12
Enter the item:75
Enter the item:42
printing the list
items25 46 12 75
42
Removing elements from the list

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:

printing original list:


01234
printing the list after the removal of first
element...0 1 3 4

Python List Built-in functions

Python provides the following built-in functions, which can be used with the lists.

SN Function Description Example

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.

2 len(list) It is used to calculate the L1 = [1,2,3,4,5,6,7,8]


length of the list. print(len(L1)
)8

3 max(list) It returns the maximum L1 = [12,34,26,48,72]


element of the list. print(max(L1))
72

4 min(list) It returns the minimum L1 = [12,34,26,48,72]


element of the list. print(min(L1))
12

5 list(seq) It converts any sequenceto str = "Johnson"s


the list. = list(str)
print(type(s))
<class list>

15 | P a g e
python list
By PS

16 | P a g e
python list
By PS

Let's have a look at the few list examples.

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:

[1, 2, 3, 55, 98, 65, 13, 29]

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:

The sum is: 67

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:

The common element is: 2

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

A tuple can be written as the collection of comma-separated (,) values enclosed


with thesmall () brackets. The parentheses are optional but it is good practice to use. A
tuple can be defined as follows.

1. T1 = (101, "Peter", 22)


2. T2 = ("Apple", "Banana", "Orange")
3. T3 = 10,20,30,40,50
4.
5. print(type(T1))
6. print(type(T2))
7. print(type(T3))

Output:

<class 'tuple'>
<class 'tuple'>
<class 'tuple'>
Note: The tuple which is created without using parentheses is also known as tuple packing.

An empty tuple can be created as follows.

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.

Consider the following example of tuple:

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:

(10, 20, 30, 40, 50, 60)


tuple1[0] = 10
tuple1[1] = 20

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:

Enter the tuple elements


...123456('1', '2', '3', '4', '5', '6')
tuple1[0] = 1
tuple1[1] = 2
tuple1[2] = 3
tuple1[3] = 4
tuple1[4] = 5
tuple1[5] = 6

A tuple is indexed in the same way as the lists. The items in the tuple can be
accessed byusing their specific index value.

Tuple indexing and slicing

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.

Consider the following example:

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.

Lets consider the following example


1. tuple1 = (1, 2, 3, 4, 5)
2. print(tuple1[-1])
3. print(tuple1[-4])
4. print(tuple1[-3:-1])
5. print(tuple1[:-1])
6. print(tuple1[-2:])

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.

Consider the following example.

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

Basic Tuple operations

The operators like concatenation (+), repetition (*), Membership (in) works in the
sameway as they work with the list. Consider the following table for more detail.

Let's say Tuple t = (1, 2, 3, 4, 5) and Tuple t1 = (6, 7, 8, 9) are declared.

Operator Descriptio Example


n
Repetition The repetition operator enables the tuple T1*2 = (1, 2, 3, 4, 5,
elements to be repeated multiple times. 1, 2, 3, 4, 5)

Concatenatio It concatenates the tuple mentioned on either side T1+T2 = (1, 2, 3, 4, 5,


n
of the operator. 6, 7, 8, 9)

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

Length It is used to get the length of the tuple. len(T1) = 5

Python Tuple inbuilt functions

SN Function Descriptio
n
1 cmp(tuple It compares two tuples and returns true if tuple1 is greater than
1,tuple2) tuple2otherwise false.

2 len(tuple) It calculates the length of the tuple.

3 max(tuple) It returns the maximum element of the tuple

4 min(tuple) It returns the minimum element of the tuple.

5 tuple(seq) It converts the specified sequence to the tuple.

Where use tuple?

Using tuple instead of list is used in the following scenario.

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.

1. [(101, "John", 22), (102, "Mike", 28), (103, "Dustin", 30)]

10 | P a g
By PS(PhD)
By PS (PhD)

List vs. Tuple

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[].

2 The List is mutable. The tuple is immutable.

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.

Unlike other collections in Python, there is no index attached to the elements of


the set,i.e., we cannot directly access any element of the set by the index. However, we
can print themall together, or we can get the list of elements by looping through the set.

Creating a set

The set can be created by enclosing the comma-separated immutable items


with the curly braces {}. Python also provides the set() method, which can be used to
create the set bythe passed sequence.

Example 1: Using curly braces


1. Days = {"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:

{'Friday', 'Tuesday', 'Monday', 'Saturday', 'Thursday', 'Sunday', 'Wednesday'}


<class 'set'>
looping through the set
elements ...Friday
Tuesday

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:

{'Friday', 'Wednesday', 'Thursday', 'Saturday', 'Monday', 'Tuesday', 'Sunday'}


<class 'set'>
looping through the set
elements ...Friday
Wednesda
yThursday
Saturday
Monday
Tuesday
Sunday

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)

Consider the following example


1. # Creating a set which have immutable
elements2. set1 = {1,2,3, "Gvkinfotech", 20.5, 14}
3. print(type(set1))
4. #Creating a set which have mutable
element5. set2 = {1,2,3,["Gvkinfotech",4]}
6. print(type(set2))

Output:

<class 'set'>

Traceback (most recent call last)


<ipython-input-5-9605bb6fbc68> in
<module>4
5 #Creating a set which holds mutable elements
----> 6 set2 =
{1,2,3,["Gvkinfotech",4]}7
print(type(set2))

TypeError: unhashable type: 'list'


In the above code, we have created two sets, the set set1 have immutable
elements andset2 have one mutable element as a list. While checking the type of set2, it
raised an error, which means set can contain only immutable elements.

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.

1. # Empty curly braces will create


dictionary2. set3 = {}

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:

Return set with unique elements: {1, 2, 4, 5, 8, 9, 10}

In the above code, we can see that set5 consisted of multiple duplicate elements
whenwe printed it remove the duplicity from the set.

Adding items to 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.

Example: 1 - Using add() method


1. Months = set(["January","February", "March", "April", "May", "June"])
2. print("\nprinting the original set ... ")
3. print(months)

5
By PS (PhD)

6
By PS (PhD)

4. print("\nAdding other months to the set...");


5. Months.add("July");
6. Months.add ("August");
7. print("\nPrinting the modified set...");
8. print(Months)
9. print("\nlooping through the set elements ... ")
10. for i in Months:
11. print(i)

Output:

printing the original set ...


{'February', 'May', 'April', 'March', 'June',

'January'}Adding other months to the set...

Printing the modified set...


{'February', 'July', 'May', 'April', 'March', 'August', 'June', 'January'}

looping through the set


elements ...February
July
May
April
March
Augus
t June
Januar
y

7
By PS (PhD)

To add more than one item in the set, Python provides the update() method. It
acceptsiterable as an argument.

Consider the following example.

Example - 2 Using update() function


1. Months = set(["January","February", "March", "April", "May", "June"])
2. print("\nprinting the original set ... ")
3. print(Months)
4. print("\nupdating the original set ... ")
5. Months.update(["July","August","September","October"]);
6. print("\nprinting the modified set ... ")
7. print(Months)

;Output:

printing the original set ...


{'January', 'February', 'April', 'May', 'June', 'March'}

updating the original set


...printing the modified
set ...
{'January' 'February' 'April' 'August' 'October' 'May' 'June' 'July' 'September' 'March'}
Removing items from the set

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)

Consider the following example.

Example-1 Using discard() method


1. months = set(["January","February", "March", "April", "May", "June"])
2. print("\nprinting the original set ... ")
3. print(months)
4. print("\nRemoving some months from the set...");
5. months.discard("January");
6. months.discard("May");
7. print("\nPrinting the modified set...");
8. print(months)
9. print("\nlooping through the set elements ... ")
10. for i in months:
11. print(i)

Output:

printing the original set ...


{'February', 'January', 'March', 'April', 'June',

'May'}Removing some months from the set...

Printing the modified set...


{'February', 'March', 'April', 'June'}

looping through the set


elements ...February
Marc
h
April
June

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.

Example-2 Using remove() function


1. months = set(["January","February", "March", "April", "May", "June"])
2. print("\nprinting the original set ... ")
3. print(months)
4. print("\nRemoving some months from the set...");
5. months.remove("January");
6. months.remove("May");
7. print("\nPrinting the modified set...");
8. print(month

s)Output:

printing the original set ...


{'February', 'June', 'April', 'May', 'January', 'March'}

Removing some months from the

set...Printing the modified set...


{'February', 'June', 'April', 'March'}

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.

1. Months = set(["January","February", "March", "April", "May", "June"])


2. print("\nprinting the original set ... ")

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:

printing the original set ...


{'June', 'January', 'May', 'April', 'February',

'March'}Removing some months from the

set...

Printing the modified set


In the above code, the last element of the Month set is March but the pop() method
removed the June and January because the set is unordered and the pop() method
could not determinethe last element of the set.

Python provides the clear() method to remove all the items from the set.

Consider the following example.

1. Months = set(["January","February", "March", "April", "May", "June"])


2. print("\nprinting the original set ... ")
3. print(Months)
4. print("\nRemoving all the items from the set...");
5. Months.clear()
6. print("\nPrinting the modified set...")
7. print(Months)

11
By PS (PhD)

Output:

printing the original set ...


{'January', 'May', 'June', 'April', 'March', 'February'}

Removing all the items from the

set...Printing the modified set...


set()

Difference between discard() and remove()

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.

Consider the following example.

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:

printing the original set ...


{'March', 'January', 'April', 'June', 'February', 'May'}

Removing items through discard() method...

printing the modified set...


{'March', 'January', 'April', 'June', 'February', 'May'}

Removing items through remove()


method...Traceback (most recent call
last):
File "set.py", line 9, in
Months.remove("Jan
")

Python Set Operations

Set can be performed mathematical operation such as union, intersection,


difference,and symmetric difference. Python provides the facility to carry out these
operations with operators or methods. We describe these operations as follows.

Union of two Sets

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)

Consider the following example to calculate the union of two sets.

Example 1: using union | operator

1. Days1 = {"Monday","Tuesday","Wednesday","Thursday", "Sunday"}


2. Days2 = {"Friday","Saturday","Sunday"}
3. print(Days1|Days2) #printing the union of the sets

Output:

{'Friday', 'Sunday', 'Saturday', 'Tuesday', 'Wednesday', 'Monday', 'Thursday'}

Python also provides the union() method which can also be used to calculate the union
of twosets. Consider the following example.

Example 2: using union() method

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:

{'Friday', 'Monday', 'Tuesday', 'Thursday', 'Wednesday', 'Sunday', 'Saturday'}

Intersection of two sets

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.

Consider the following example.

Example 1: Using & operator

1. Days1 = {"Monday","Tuesday", "Wednesday", "Thursday"}


2. Days2 = {"Monday","Tuesday","Sunday", "Friday"}
3. print(Days1&Days2) #prints the intersection of the two sets

Output:

{'Monday', 'Tuesday'}

15
By PS (PhD)

Example 2: Using intersection() method

1. set1 = {"Devansh","John", "David", "Martin"}


2. set2 = {"Steve", "Milan", "David", "Martin"}
3. print(set1.intersection(set2)) #prints the intersection of the two sets

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

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

The intersection_update() method is different from the intersection() method


since it modifies the original set by removing the unwanted items, on the other hand, the
intersection()method returns a new set.

16
By PS (PhD)

Consider the following example.

1. a = {"Devansh", "bob", "castle"}


2. b = {"castle", "dude", "emyway"}
3. c = {"fuson", "gaurav",
"castle"}4.
5. a.intersection_update(b, c)
6.
7. print(a)

Output:

{'castle'}

Difference between the two sets

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)

Consider the following example.

Example 1 : Using subtraction ( - ) operator

1. Days1 = {"Monday", "Tuesday", "Wednesday", "Thursday"}


2. Days2 = {"Monday", "Tuesday", "Sunday"}
3. print(Days1-Days2) #{"Wednesday", "Thursday" will be printed}

Output:

{'Thursday', 'Wednesday'}

Example 2 : Using difference() method

1. Days1 = {"Monday", "Tuesday", "Wednesday", "Thursday"}


2. Days2 = {"Monday", "Tuesday", "Sunday"}
3. print(Days1.difference(Days2)) # prints the difference of the two sets Days1 and Days2

Output:

{'Thursday', 'Wednesday'}

Symmetric Difference of two sets

The symmetric difference of two sets is calculated by ^


operator or symmetric_difference() method. Symmetric difference of sets, it removes
that element which is present in both sets. Consider the following example:

18
By PS (PhD)

Example - 1: Using ^ operator

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}

Example - 2: Using symmetric_difference() method

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.

Consider the following example.

1. Days1 = {"Monday", "Tuesday", "Wednesday", "Thursday"}


2. Days2 = {"Monday", "Tuesday"}
3. Days3 = {"Monday", "Tuesday",
"Friday"}4.
5. #Days1 is the superset of Days2 hence it will print true.
6. print
(Days1>Days2)7.
8. #prints false since Days1 is not the subset of Days2
9. print
(Days1<Days2)10.
11. #prints false since Days2 and Days3 are not equivalent
12. print (Days2 == Days3)

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.

Consider the following example to create the frozen set.

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

printing the content of frozen


set...1
2
3
4
5
Traceback (most recent call last):
File "set.py", line 6, in <module>
Frozenset.add(6) #gives an error since we can change the content of Frozenset after
creationAttributeError: 'frozenset' object has no attribute 'add'

22
By PS (PhD)

Frozenset for the dictionary

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.

Consider the following example.

1. Dictionary = {"Name":"John", "Country":"USA", "ID":101}


2. print(type(Dictionary))
3. Frozenset = frozenset(Dictionary); #Frozenset will contain the keys of the dictionary
4. print(type(Frozenset))
5. for i in Frozenset:
6. print(i)

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:

Enter the number you want to


remove:12After Removing: {1, 2, 3, 4,

Example - 2: Write a program to add multiple elements to the set.

1. set1 = set([1,2,4,"John","CS"])
2. set1.update(["Apple","Mango","Grapes"])
3. print(set1)

Output:

{1, 2, 4, 'Apple', 'John', 'CS', 'Mango', 'Grapes'}

Example - 3: Write a program to find the union between two set.

1. set1 = set(["Peter","Joseph", 65,59,96])


2. set2 = set(["Peter",1,2,"Joseph"])
3. set3 = set1.union(set2)
4. print(set3)

Output:

{96, 65, 2, 'Joseph', 1, 'Peter', 59}

Example- 4: Write a program to find the intersection between two sets.

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}

Example - 5: Write the program to add element to the frozenset.

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:

TypeError: 'frozenset' object does not support item assignment

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

Python contains the following methods to be used with the sets.

SNO Method Description


It adds an item to the set. It has no effect if
the
1 add(item)
item is already present in the set.
2 clear() It deletes all the items from the set.
3 copy() It returns a shallow copy of the set.
It modifies this set by removing all the items
4 difference_update( ) that are also present in the specified sets.
5 discard(item) It removes the specified item from the set.
It returns a new set that contains only the
6 intersection() common elements of both the sets. (all the
setsif more than two are specified).
It removes the items from the original set
that
7 intersection_update( )
are not present in both the sets (all the sets
ifmore than one are specified).
8 Isdisjoint( ) Return True if two sets have a null
intersection.
9 Issubset( ) Report whether another set contains this
set.
10 Issuperset( ) Report whether this set contains another
set.

27
By PS (PhD)

Remove and return an arbitrary set element


11 pop() that is the last element of the set. Raises

28
By PS (PhD)

KeyError if the set is empty.


Remove an element from a set; it must be a
12 remove(item) member. If the element is not a member,
raise a
KeyError.
Remove an element from a set; it must be a
13 symmetric_difference( ) member. If the element is not a member,
raise a
KeyError.
Update a set with the symmetric difference
of
14 symmetric_difference_update( )
itself and another.
Return the union of sets as a new set.
15 union( ) (i.e. all elements that are in either set.)
16 update() Update a set with the union of itself and
others.

29

You might also like