You are on page 1of 26

Python Programming

Introduction to Python
Akhil M. Jaiswal
9028637523
Introduction to Python:

What is Python Language?

Python is an interpreted, object-oriented, high-level programming language with dynamic


semantics.

Its high-level built in data structures, combined with dynamic typing and dynamic binding,
make it very attractive for Rapid Application Development, as well as for use as a scripting or
glue language to connect existing components together.

Python's simple, easy to learn syntax emphasizes readability and therefore reduces the cost
of program maintenance.

Python supports modules and packages, which encourages program modularity and code
reuse.

The Python interpreter and the extensive standard library are available in source or binary
form without charge for all major platforms, and can be freely distributed

History of Python: Guido van Rossum began working on Python in the late 1980s, as a
successor to the ABC programming language, and first released it in 1991 as Python 0.9.0.

Python 2.0 was released in 2000 and introduced new features, such as list
comprehensions and a garbage collection system using reference counting and was
discontinued with version 2.7.18 in 2020.

Python 3.0 was released in 2008 and was a major revision of the language that is not
completely backward-compatible and much Python 2 code does not run unmodified on
Python 3.

Guido Van Rossum

Prof. Akhil M. Jaiswal 9028637523


2
Features of Python: Following are the notable features of Python:
1) Easy to Learn and Use: Python is easy to learn as compared to other programming
languages. Its syntax is straightforward and much the same as the English language. There is no use
of the semicolon or curly-bracket, the indentation defines the code block. It is the recommended
programming language for beginners.

2) Expressive Language: Python can perform complex tasks using a few lines of code. A simple
example, the hello world program you simply type print("Hello World"). It will take only one line to
execute, while Java or C takes multiple lines.

3) Interpreted Language: Python is an interpreted language; it means the Python program is


executed one line at a time. The advantage of being interpreted language, it makes debugging easy
and portable.

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. It enables
programmers to develop the software for several competing platforms by writing a program only once.

5) Free and Open Source: Python is freely available for everyone. It is freely available on its
official website www.python.org. It has a large community across the world that is dedicatedly working
towards make new python modules and functions. Anyone can contribute to the Python community.
The open-source means, "Anyone can download its source code without paying any penny."

6) Object-Oriented Language: Python supports object-oriented language & concepts of


classes & objects come into existence. It supports inheritance, polymorphism, encapsulation etc. The
object oriented procedure helps to programmer to write reusable code & develop applications.

7) Extensible: It implies that other languages such as C/C++ can be used to compile the code and
thus it can be used further in our Python code. It converts the program into byte code, and any
platform can use that byte code.

8) Large Standard Library: It provides a vast range of libraries for the various fields such as
machine learning, web developer, and also for the scripting. There are various machine learning
libraries, such as Tensor flow, Pandas, Numpy, Keras, and Pytorch, etc. Django, flask, pyramids are
the popular framework for Python web development.

9) GUI Programming Support: Graphical User Interface is used for the developing Desktop
application. PyQT5, Tkinter, Kivy are the libraries which are used for developing the web application.

10) Integrated: It can be easily integrated with languages like C, C++, and JAVA, etc. Python
runs code line by line like C, C++ Java. It makes easy to debug the code.

11) Embeddable: The code of the other programming language can use in the Python source
code. We can use Python source code in another programming language as well. It can embed other
language into our code.

12) Dynamic Memory Allocation : In Python, we don't need to specify the data-type of the
variable. When we assign some value to the variable, it automatically allocates the memory to the
variable at run time. Suppose we are assigned integer value 15 to x, then we don't need to write int x =
15. Just write x = 15.

Prof. Akhil M. Jaiswal 9028637523


3
Python Building Blocks: Following are the basic Building Blocks of Python:
1. Keywords
2. Identifiers
3. Indentation
4. Comments
5. Variables

1. Keywords: Python reserves 35 keywords in 3.8 versions for its


use. Keywords are case sensitive in python. You can’t use a keyword as variable
name, function name or any other identifier name. Here is the list of keywords in
python. All keywords are in lowercase except “False”, “None” & “True”.

async
await

2. Identifiers: An identifier is a name given to entities like class, functions,


variables, etc. It helps to differentiate one entity from another.

A Programmer should always choose a meaningful name for their variable.

1. Identifiers can be combination of both letters in lowercase (a to z) or uppercase (A to Z) or


digits (0 to 9) or an underscore _. Names like myClass, var_1 and print_this_to_screen, all
are valid example. but they cannot start with a number. So, variable1 is valid while 1variable
is a invalid name.
2. You can’t use special characters like !, @, #, $, % etc. in variable name.
3. Python keywords cannot be used as variable name.
4. An identifier can be of any length and can use uppercase letters for variable names but it is
always perfectly fine to begin variable names with a lowercase letter.
5. Identifiers cannot contain white blank space such as, Total price is invalid but can use
underscore character (_) in the name. For example, Total_price is valid example.

If you give a variable an illegal name, you will get a syntax error:
1var=20 //starts with number
class=5 //keyword used
global=10 //keyword used
all@1=100 //special character used
Prof. Akhil M. Jaiswal 9028637523
4

3. Python Indentation
Indentation refers to the spaces at the beginning of a code line.

Where in other programming languages the indentation in code is for readability only,
the indentation in Python is very important.

Python uses indentation to indicate a block of code.

Indentation is a very important concept of Python because without proper indenting


the Python code, you will end up seeing IndentationError and the code will not get
compiled.

Example: if 5 > 2:
print("Five is greater than two!")

Python will give you an error if you skip the indentation:

Example: Syntax Error:

if 5 > 2:
print("Five is greater than two!")

The number of spaces is up to you as a programmer, but it has to be at least one.

if 5 > 2:
print("Five is greater than two!")
if 5 > 2:
print("Five is greater than two!")

4. Python Comments:
Comments can be used to explain Python code.

Comments are Non Executable Part & Ignored by Python Compiler.

Comments can be used to make the code more readable.

Comments can be used to prevent execution when testing code.

Types of Comment: There are 2 types Comment:

1) Single Line Comment

2) Multiple Line Comment


Prof. Akhil M. Jaiswal 9028637523
5
1) Single Line Comment- Creating Single line Comment

 Comments starts with a #, and Python will ignore them:

Example: #This is a comment


print("Hello, World!")

 Comments can be placed at the end of a line, and Python will ignore the rest of the
line:

print("Hello, World!") #This is a comment

 A comment does not have to be text that explains the code, it can also be used to
prevent Python from executing code:

#print("Hello, World!")
print("Cheers, Mate!")

2) Multi Line Comments: To add a multiline comment you could insert a # for each line:

Example
#This is a comment
#written in
#more than just one line
print("Hello, World!")

Or, not quite as intended, you can use a multiline string.

Since Python will ignore string literals that are not assigned to a variable, you can add
a multiline string (triple quotes) in your code, and place your comment inside it:

Example
"""
This is a comment
written in
more than just one line
"""
print("Hello, World!")

As long as the string is not assigned to a variable, Python will read the code, but then
ignore it, and you have made a multiline comment.

Prof. Akhil M. Jaiswal 9028637523


6

5. Python Variables
Variables are containers for storing data values.

Creating Variables
Python has no command for declaring a variable.

A variable is created the moment you first assign a value to it.

Example
x = 5
y = "John" or ‘John’
print(x)
print(y)

Variables do not need to be declared with any particular type, and can even change type after they
have been set.

Example
x = 4 # x is of type int
x = "Sally" # x is now of type str
print(x)

Casting
If you want to specify the data type of a variable, this can be done with casting.

Example
x = str(3) # x will be '3'
y = int(3) # y will be 3
z = float(3) # z will be 3.0

Get the Type


You can get the data type of a variable with the type() function.

Example
x = 5
y = "John"
print(type(x))
print(type(y))
Prof. Akhil M. Jaiswal 9028637523
7

Single or Double Quotes?


String variables can be declared either by using single or double quotes:

Example x = "John" y=”H”


# is the same as
x = 'John'

Case-Sensitive: Variable names are case-sensitive.


Example: This will create two variables:
a = 4
A = "Sally"
#A will not overwrite a

Practice Programs:
1) Python Script to accept Name, RollNo & marks of 3 subjects of a student & display
Sum, Average & Percentage.

2) Python Script to display Balance of account & perform Deposit & Withdraw (amount to
be accepted from user)

3) Python script to accept Price per items & Number of items for Two. Calculate &
display Total Bill.

Program1:-

nm=str(input("Enter Name of Student"))

rn=int(input("Enter Roll Number"))

s1=int(input("Enter Marks of Physics"))

s2=int(input("Enter Marks of CHem"))

s3=int(input("Enter Marks of Maths"))

t=int(s1+s2+s3)

avg=float(t/3)

print("Total Marks=",t)

print("Average =",avg)

Prof. Akhil M. Jaiswal 9028637523


8

Python Data Types:

 Variables can store data of different types, and different types can
do different things.
 Since everything is an object in Python programming, data types are
actually classes and variables are instance (object) of these classes.
 Data types are the classification or categorization of data items.
 It represents the kind of value that tells what operations can be
performed on a particular data.

Following are the standard or built-in data type of Python:-

1. Numbers.
2. Strings.
3. Tuples.
4. Lists.
5. Dictionary.

1. Numbers: Number stores numeric values. The integer, float, and complex values
belong to a Python Numbers data-type. Python provides the type() function to know the
data-type (class) of the variable(instance). Similarly, the isinstance() function is used to
check an object belongs to a particular class.

Python supports three types of numeric data.

1. int - Integer value can be any length such as integers 10, 2, 29, -20, -150 etc. Python
has no restriction on the length of an integer. Its value belongs to int
2. float - Float is used to store floating-point numbers like 1.9, 9.902, 15.2, etc. It is
accurate upto 15 decimal points.
3. complex - A complex number contains an ordered pair, i.e., x + iy where x and y denote
the real and imaginary parts, respectively. The complex numbers like 2.14j, 2.0 + 2.3j,
etc.

Python creates Number objects when a number is assigned to a variable.

Prof. Akhil M. Jaiswal 9028637523


9
For example;

a = int(5 )
print("The type of a", type(a))

b = float(40.5 )
print("The type of b", type(b))

c = complex(1+3j )
print("The type of c", type(c))
print(" c is a complex number", isinstance(1+3j,complex))

Output:

The type of a <class 'int'>


The type of b <class 'float'>
The type of c <class 'complex'>
c is complex number: True

Ex: Write a python script to accept an Int, float & complex value & display its Type & instance.

 Sequence Type

String: The string can be defined as the sequence of characters represented in the
quotation marks. In Python, we can use single, double, or triple quotes to define a string.
Strings, however, are immutable.

String handling in Python is a straightforward task since Python provides built-in


functions and operators to perform operations in the string.

 Concatenation Operator: In the case of string handling, the operator + is used to


concatenate two strings as the operation "hello"+" python" returns "hellopython".
 Repetition operator: The operator * is known as a repetition operator as the
operation "Python" *2 returns 'Python Python'.
 Slicing Operator: We can use slice [:] operators to access the data of the String or list
at or from particular location.

The following example illustrates the string in Python.

Example - 1

str = string using double quotes


print(str)
s = '''''A multiline
string'''
print(s)

Output: string using double quotes


A multiline
string
Prof. Akhil M. Jaiswal 9028637523
10
Consider the following example of string handling.

Example - 2

str1 = “hello Python” #string str1


str2 = 'how are you' #string str2
print (str1[0:2]) #printing first two character using slice operator
print (str1[4]) #printing 4th character of the string
print (str1[-1]) #prints last character
print (str1*2) #printing the string twice
print (str1 + str2) #printing the concatenation of str1 and str2

Output:he
o
n
hello Pythonhello Python
hello Python how are you

Built-in DataTypes:
1. Python Tuples: ( ) -tupledemo.py
 Tuples are used to store multiple items in a single variable.
 Tuple is one of 4 built-in data types in Python used to store collections of data, the other 3 are List, Set,
and Dictionary, all with different qualities and usage.
 A tuple is a collection which is ordered and unchangeable/ Immutable.
 Tuples are written with round brackets. ()
 Tuple items allow duplicate values.
 Tuple items are indexed, the first item has index [0], the second item has index [1] etc.

Example: Create a Tuple:

thistuple = ("apple", "banana", "cherry")


print(thistuple)

The tuple() Constructor: It is also possible to use the tuple() constructor to make a tuple.
Example: Using the tuple() method to make a tuple:

thistuple = tuple(("apple", "banana", "cherry")) # note the double round-brackets


print(thistuple)

Ordered: When we say that tuples are ordered, it means that the items have a defined order, and
that order will not change.

Unchangeable: Tuples are unchangeable, meaning that we cannot change, add or remove items
after the tuple has been created.

Prof. Akhil M. Jaiswal 9028637523


11

Allow Duplicates: Since tuple are indexed, tuples can have items with the same value:

Example: Tuples allow duplicate values:

thistuple = ("apple", "banana", "cherry", "apple", "cherry")


print(thistuple)

Tuple Length: To determine how many items a tuple has, use the len() function:

Example: Print the number of items in the tuple:

thistuple = ("apple", "banana", "cherry")


print(len(thistuple))

Create Tuple With One Item

To create a tuple with only one item, you have to add a comma after the item, otherwise Python will not
recognize it as a tuple.

Example: One item tuple, remember the commma:

thistuple = ("apple",)
print(type(thistuple))

#NOT a tuple
thistuple = ("apple")
print(type(thistuple))

Tuple Items - Data Types: Tuple items can be of any data type:

Example: String, int and boolean data types:

tuple1 = ("apple", "banana", "cherry")


tuple2 = (1, 5, 7, 9, 3)
tuple3 = (True, False, False)

A tuple can contain different data types:

Example: A tuple with strings, integers and boolean values:

tuple1 = ("abc", 34, True, 40, "male")

type()

From Python's perspective, tuples are defined as objects with the data type 'tuple':

<class 'tuple'>

Example

Data type of a tuple:

mytuple = ("apple", "banana", "cherry")


print(type(mytuple))

Prof. Akhil M. Jaiswal 9028637523


12

2. Python List: [ ] -listdemo.py

Lists are used to store multiple items in a single variable.

Lists are one of 4 built-in data types in Python used to store collections of data, the other 3 are Tuple, Set,
and Dictionary, all with different qualities and usage.

Lists are created using square brackets [ ] where items are separated by commas (,):

Example: mylist = ["apple", "banana", "cherry"]

Create a List:

thislist = ["apple", "banana", "cherry"]


print(thislist)

The list() Constructor


It is also possible to use the list() constructor when creating a new list.

Example: Using the list() constructor to make a List:


thislist = list(("apple", "banana", "cherry")) # note the double round-brackets
print(thislist)

List Items
List items are ordered, Changeable/Mutable, and allow duplicate values.

List items are indexed, the first item has index [0], the second item has index [1] etc

Ordered
When we say that lists are ordered, it means that the items have a defined order, and that order will not
change.

If you add new items to a list, the new items will be placed at the end of the list.

Note: There are some list methods that will change the order, but in general: the order of the items will not
change.

Changeable
The list is changeable, meaning that we can change, add, and remove items in a list after it has been
created.

Prof. Akhil M. Jaiswal 9028637523


13

Allow Duplicates
Since lists are indexed, lists can have items with the same value:

Example: Lists allow duplicate values:


thislist = ["apple", "banana", "cherry", "apple", "cherry"]
print(thislist)

List Length
To determine how many items a list has, use the len() function:

Example: Print the number of items in the list:

thislist = ["apple", "banana", "cherry"]


print(len(thislist))

List Items - Data Types


List items can be of any data type:

Example: String, int and boolean data types:

list1 = ["apple", "banana", "cherry"]


list2 = [1, 5, 7, 9, 3]
list3 = [True, False, False]

A list can contain different data types:

Example: A list with strings, integers and boolean values:

list1 = ["abc", 34, True, 40, "male"]

type()
From Python's perspective, lists are defined as objects with the data type 'list':

<class 'list'>

Example: Data type of a list:

mylist = ["apple", "banana", "cherry"]


print(type(mylist))

Prof. Akhil M. Jaiswal 9028637523


14

Python - Add List Items


Append Items: To add an item to the end of the list, use the append() method:

Example: Using the append() method to append an item:

thislist = ["apple", "banana", "cherry"]


thislist.append("orange")
print(thislist)

Insert Items: To insert/ add a new list item at a specified index & shift reaming items, use the insert()
method.

The insert() method inserts an item at the specified index:

Example: Insert an item as the second position & Shift rmaining items & increment items by 1 :

thislist = ["apple", "banana", "cherry"]


thislist.insert(1, "orange")
print(thislist)

Note: As a result of the examples above, the lists will now contain 4 items.

Extend List: To append elements from another list to the current list, use the extend() method.
Example: Add the elements of tropical to thislist:

thislist = ["apple", "banana", "cherry"]


tropical = ["mango", "pineapple", "papaya"]
thislist.extend(tropical)
print(thislist)

The elements will be added to the end of the list.

Add Any Iterable

The extend() method does not have to append lists, you can add any iterable object (tuples, sets, dictionaries
etc.).

Example

Add elements of a tuple to a list:

thislist = ["apple", "banana", "cherry"]


thistuple = ("kiwi", "orange")
thislist.extend(thistuple)
print(thislist)

Prof. Akhil M. Jaiswal 9028637523


15

Change Item Value: To change the value of a specific item, refer to the index number:

Example: Change the second item:

thislist = ["apple", "banana", "cherry"]


thislist[1] = "blackcurrant"
print(thislist)

Change a Range of Item Values: To change the value of items within a specific range, define a list
with the new values, and refer to the range of index numbers where you want to insert the new values:

Example: Change the values "banana" and "cherry" with the values "blackcurrant" and "watermelon":

thislist = ["apple", "banana", "cherry", "orange", "kiwi", "mango"]


thislist[1:3] = ["blackcurrant", "watermelon"]
print(thislist)

If you insert more items than you replace, the new items will be inserted where you specified, and the remaining items will move
accordingly:

Example: Change the second value by replacing it with two new values:
thislist = ["apple", "banana", "cherry"]
thislist[1:2] = ["blackcurrant", "watermelon"]
print(thislist)

Note: The length of the list will change when the number of items inserted does not match the number of items
replaced.

If you insert less items than you replace, the new items will be inserted where you specified, and the remaining
items will move accordingly:

Example: Change the second and third value by replacing it with one value:

thislist = ["apple", "banana", "cherry"]


thislist[1:3] = ["watermelon"]
print(thislist)

Insert Items: To insert a new list item, without replacing any of the existing values, we can use
the insert() method. The insert() method inserts an item at the specified index:
Example: Insert "watermelon" as the third item:
thislist = ["apple", "banana", "cherry"]
thislist.insert(2, "watermelon")
print(thislist)

Note: As a result of the example above, the list will now contain 4 items.

Prof. Akhil M. Jaiswal 9028637523


16

3. Python Dictionary: {key:value}


Dictionaries are used to store data values in “key:value” pairs, and can be referred to by using the key name.

A dictionary is a collection which is ordered*, unindexed, changeable and does not allow duplicates.

*As of Python version 3.7, dictionaries are ordered. In Python 3.6 and earlier, dictionaries are unordered.

Dictionaries are written with curly brackets {}, and have keys and values:

Key & Values both can be of different Data Type, where items are separated by , (comma)

Example: Create and print a dictionary:


thisdict = { "brand": "Ford",
"model": "Mustang",
"year": 1964
}
print(thisdict)

Dictionary Items
Example: Print the "brand" value of the dictionary:

thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
print(thisdict["brand"])

Ordered or Unordered?
As of Python version 3.7, dictionaries are ordered. In Python 3.6 and earlier, dictionaries are unordered.

When we say that dictionaries are ordered, it means that the items have a defined order, and that order will not change.

Unordered means that the items does not have a defined order, you cannot refer to an item by using an index.

Changeable
Dictionaries are changeable, meaning that we can change, add or remove items after the dictionary has been
created.

Duplicates Not Allowed

Dictionaries cannot have two items with the same key:

Example: Duplicate values will overwrite existing values:

thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964,
"year": 2020
}
print(thisdict)

Prof. Akhil M. Jaiswal 9028637523


17

Dictionary Length: To determine how many items a dictionary has, use the len() function:

Example: Print the number of items in the dictionary:

print(len(thisdict))

Dictionary Items - Data Types: The values in dictionary items can be of any data type:

Example: String, int, boolean, and list data types:

thisdict = {
"brand": "Ford",
"electric": False,
"year": 1964,
"colors": ["red", "white", "blue"]
}
print(type(thisdict)

type(): From Python's perspective, dictionaries are defined as objects with the data type 'dict':
Example: Print the data type of a dictionary:

thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
print(type(thisdict))

<class 'dict'>

Python Dictionary Methods: Methods that are available with a dictionary are tabulated below. Some of them have already
been used in the above examples.

Method Description
clear()
Removes all items from the dictionary.

copy() Returns a shallow copy of the dictionary.

fromkeys(seq[, v]) Returns a new dictionary with keys from seq and value equal to v (defaults to None ).

get(key[,d]) Returns the value of the key . If the key does not exist, returns d (defaults to None ).

items() Return a new object of the dictionary's items in (key, value) format.

keys() Returns a new object of the dictionary's keys.

pop(key[,d]) Removes the item with the key and returns its value or d if key is not found. If d is not provided
and the key is not found, it raises KeyError .

popitem() Removes and returns an arbitrary item (key, value). Raises KeyError if the dictionary is empty.

setdefault(key[,d]) Returns the corresponding value if the key is in the dictionary. If not, inserts the key with a value
of d and returns d (defaults to None ).
update([other]) Updates the dictionary with the key/value pairs from other , overwriting existing keys.
values()
Returns a new object of the dictionary's values

Prof. Akhil M. Jaiswal 9028637523


18
Dictionary Operations:

Accessing Elements from Dictionary


While indexing is used with other data types to access values, a dictionary uses keys . Keys can be used either inside square
brackets [] or with the get() method.

Example: thisdict = { "brand": "Ford", "model": "Mustang","year": 1964}

print(thisdict.get('year')) #print value of key 'year' using get() method

Changing and Adding Dictionary elements


Dictionaries are mutable. We can add new items or change the value of existing items using an assignment operator.

If the key is already present, then the existing value gets updated. In case the key is not present, a new (key: value) pair is added to
the dictionary.

Example:
thisdict = { "brand": "Ford", "model": "Mustang", "year": 1964}

# update value
thisdict['year'] = 1970

print(thisdict)

# add item
thisdict['address'] = 'Downtown'

print(thisdict)

Removing elements from Dictionary:


1. pop(): We can remove a particular item in a dictionary by using the pop() method. This method
removes an item with the provided key and returns the value.
2. popitem(): method can be used to remove and return an arbitrary (key, value) item pair from
the dictionary.
3. clear(): All the items can be removed at once, using the clear() method.
4. del: We can also use the del keyword to remove individual items or the entire dictionary itself.

Example: thisdict = { "brand": "Ford", "model": "Mustang", "year": 1964}

#Remove an entry using pop() method


thisdict.pop("year")
print(thisdict)

#popitem() removes an arbitary (key:value)


thisdict.popitem()
print(thisdict)

#clear() method cleares all Items


thisdict.clear()
print(thisdict)

#'del' keyword delets the Dictionary


del thisdict
print(thisdict) #error message

Prof. Akhil M. Jaiswal 9028637523


19

4. Python Sets: Sets are used to store multiple items in a single variable inside curly
braces “{}” separated by commas “,”.

Example: # set with integer datatype


my_set1 = {1, 2, 3}
print(my_set1)

# set of mixed datatypes


my_set2 = {1.0, "Hello", (1, 2, 3)} #list items not allowed
print(my_set2)

 Set is one of 4 built-in data types in Python used to store collections of data, the other 3
are List, Tuple, and Dictionary, all with different qualities and usage.
 A set is a collection which is both unordered and unindexed. (Dict)
 Set elements are unique & do not allow duplicates. (Dict)
 Set itself can be modified but elements of sets are unchangeable / immutable, but you can
add new items or remove existing items.
 Set items can appear in a different order every time you use them, and cannot be referred to
by index or key.
 Sets can also be used to perform mathematical set operations like union, intersection,
symmetric difference, etc.

set() Constructor: It is also possible to use the set() constructor to make a set.
Example: Using the set() constructor to make a set:
thisset = set(("apple", "banana", "cherry")) # note the double round-brackets
print(thisset)

Duplicates Not Allowed: Sets cannot have two items with the same value.
Example: Duplicate values will be ignored:

thisset = {"apple", "banana", "cherry", "apple"}


print(thisset) #will omit duplicate items

Output: {'cherry', 'apple', 'banana'}

Get the Length of a Set: To determine how many items a set has, len() method is used
Example: Get the number of items in a set:
thisset = {"apple", "banana", "cherry"}
print(len(thisset))

Output: 3

Prof. Akhil M. Jaiswal 9028637523


20

type(): From Python's perspective, sets are defined as objects with the data type 'set':
Example: determine data type of a set-
myset = {"apple", "banana", "cherry"}
print(type(myset))

Output: <class 'set'>

Access Items: You cannot access items in a set by referring to an index or a key.

But you can loop through the set items using a for loop, or ask if a specified value is present in a set,
by using the in keyword.

Example: Loop through the set, and print the values:

thisset = {"apple", "banana", "cherry"}

for x in thisset:
print(x)

Add Items: Once a set is created, you cannot change its items, but you can add new items using add()
Example: Add an item to a set, using the add() method at arbitrary position:
thisset = {"apple", "banana", "cherry"}

thisset.add("orange")
print(thisset) # will add “orange” at random position

Add Sets: To add items from another set into the current set, use the update() method.
Example: Add elements from my_set2 in my_set1:

my_set1 = {"apple", "banana", "cherry"}


my_set2 = {"pineapple", "mango", "papaya"}

my_set1.update(my_set2)
print(my_set1) #will add all items of my_set2 in my_set1

Add Any Iterable: The object in the update() method does not have be a set, it can be any iterable
object (tuples, lists, dictionaries etc.).

Example: Add elements of a list to at set:


thisset = {"apple", "banana", "cherry"} #set
mylist = ["kiwi", "orange"] #a List

thisset.update(mylist) # will add all list items to set


print(thisset)

Output: {'orange', 'kiwi', 'apple', 'banana', 'cherry'}

Prof. Akhil M. Jaiswal 9028637523


21
Remove Set Items: To remove an item in a set, use the remove(), or discard() method.

Example: Remove "banana" by using the remove() method:

thisset = {"apple", "banana", "cherry"}


thisset.remove("banana")
print(thisset)

Note: If the item to remove does not exist, remove() will raise an error.

Example: Remove "banana" by using the discard() method:


thisset = {"apple", "banana", "cherry"}
thisset.discard("banana")
print(thisset)

Note: If the item to remove does not exist, discard() will NOT raise an error.

pop() method: We can also use the pop() method to remove an item, but this method will remove
the last item. Remember that sets are unordered, so you will not know what item that gets removed.

The return value of the pop() method is the removed item.

Example: Remove the last item by using the pop() method:


thisset = {"apple", "banana", "cherry"}
x = thisset.pop()
print(x)
print(thisset)

Note: Sets are unordered, so when using the pop() method, you do not know which item that gets
removed.

clear()method: This method will delete all the items from the set and will empty it but will not
delete the set

Example: The clear() method empties the set:


thisset = {"apple", "banana", "cherry"}
thisset.clear()
print(thisset)

del keyword: It will delete the complete set.

Example: The del keyword will delete the set completely:

thisset = {"apple", "banana", "cherry"}


del thisset
print(thisset)

Prof. Akhil M. Jaiswal 9028637523


22

Set Methods: Python has a set of built-in methods that you can use on sets.
Method Description

add() Adds an element to the set

clear() Removes all the elements from the set

copy() Returns a copy of the set

difference() Returns a set containing the difference between two or more sets

difference_update() Removes the items in this set that are also included in another given set

discard() Remove the specified item

intersection() Returns a set, that is the intersection of two other sets

intersection_update() Remove items in this set that are not present in other, specified set(s)

isdisjoint() Returns whether two sets have a intersection or not

issubset() Returns whether another set contains this set or not

issuperset() Returns whether this set contains another set or not

pop() Removes an element from the set

remove() Removes the specified element

symmetric_difference() Returns a set with the symmetric differences of two sets

symmetric_difference_update() inserts the symmetric differences from this set and another

union() Return a set containing the union of sets

update() Update the set with the union of this set and others

Set Operations:-

Prof. Akhil M. Jaiswal 9028637523


23

Python Set Operations


Sets can be used to carry out mathematical set operations like union, intersection, difference and
symmetric difference. We can do this with operators or methods.

Let us consider the following two sets for the following operations.

>>> A = {1, 2, 3, 4, 5}
>>> B = {4, 5, 6, 7, 8}

1. Set Union ( | ) :- Union of A and B is a set of all elements from both sets.

Set Union in Python: Union of A and B is a set of all elements from both sets.

Union is performed using | vertical bar operator. Same can be done using the union() method.

# Set union method


# initialize A and B
A = {1, 2, 3, 4, 5}
B = {4, 5, 6, 7, 8}

# use | operator
print(A | B)
#similarly
C= A. union( B )
print(c)

Output

{1, 2, 3, 4, 5, 6, 7, 8}

Similarly Using union() method.

Example:
>>> A.union(B)
{1, 2, 3, 4, 5, 6, 7, 8}

# use union function on B


>>> B.union(A)
{1, 2, 3, 4, 5, 6, 7, 8}

Prof. Akhil M. Jaiswal 9028637523


24

2. Set Intersection: Intersection of sets A and B is a set of elements that are common in both the sets.

Set Intersection in Python: Intersection of A and B is a set of elements that are common in both the sets.
Intersection is performed using & operator. Same can be accomplished using the intersection() method.

# Intersection of sets
# initialize A and B
A = {1, 2, 3, 4, 5}
B = {4, 5, 6, 7, 8}

# use & operator


# Output: {4, 5}
print(A & B)
#Similarly
c= A.intersection(B)
print(c)

Output

{4, 5}

Try the following examples on Python shell.

# use intersection function on A


>>> A.intersection(B)
{4, 5}

# use intersection function on B


>>> B.intersection(A)
{4, 5}

Prof. Akhil M. Jaiswal 9028637523


25

3. Set Difference : Difference of the set B from set A(A - B) is a set of elements that are only
in A but not in B. Similarly, B - A is a set of elements in B but not in A.

Set Difference in Python: Difference of the set B from set A ( A - B ) is a set of elements that are only
in A but not in B . Similarly, B - A is a set of elements in B but not in A .

Difference is performed using - operator. Same can be accomplished using the difference() method.
# Difference of two sets
# initialize A and B
A = {1, 2, 3, 4, 5}
B = {4, 5, 6, 7, 8}

# use - operator on A
# Output: {1, 2, 3}
print(A - B)
#similarly
C= A.difference(B)
print(c)

Output

{1, 2, 3}

Try the following examples on Python shell.

# use difference function on A


>>> A.difference(B)
{1, 2, 3}

# use - operator on B
>>> B - A
{8, 6, 7}

# use difference function on B


>>> B.difference(A)
{8, 6, 7}

Prof. Akhil M. Jaiswal 9028637523


26

4. Set Symmetric Difference:

Set Symmetric Difference in Python: Symmetric Difference of A and B is a set of elements


in A and B but not in both (excluding the intersection).

Symmetric difference is performed using ^ tidle operator. Same can be accomplished using the
method symmetric_difference() .

# Symmetric difference of two sets


# initialize A and B
A = {1, 2, 3, 4, 5}
B = {4, 5, 6, 7, 8}

# use ^ operator
# Output: {1, 2, 3, 6, 7, 8}
print(A ^ B)
# using symmetric_difference()
C = A.symmetric_difference(B)
print(c)

Output

{1, 2, 3, 6, 7, 8}

Prof. Akhil Jaiswal

Ph.D. (Pursuing), M.E., B.E.

C,C++, JAVA, PYTHON, ADVANCE JAVA,

DATA STRUCTURES, DBMS, SOFTWARE ENGINEERING/ TESTING

9028637523

Prof. Akhil M. Jaiswal 9028637523

Copy protected with Online-PDF-No-Copy.com

You might also like