Download as pdf or txt
Download as pdf or txt
You are on page 1of 44

LJIET Sem-5 PDS (3150713)

Chapter 1: Overview of Python and Data


Structures
 Python is a widely used general-purpose, high level, interpreted, dynamic programing language.
 Python laid its foundation in the late 1980s.
 The implementation of Python was started in December 1989 by Guido Van Rossum at CWI in
Netherland.

 Features of Python:
1. It is Simple
2. Easy to learn
3. Free and Open source
4. High level language: Strong abstraction from the details of the computer like registers,
memory address and call stacks.
5. Compiled as well as Interpreted: For the most part, Python is an interpreted language and
not a compiled one, although compilation is a step. Python code, written in .py file is first
compiled to what is called bytecode which is stored with a .pyc or .pyo format. This bytecode
is a low-level set of instructions that can be executed by an interpreter.
6. Embedded: 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.
7. Extensible ( Support for other languages ): Python is an Extensible language. We can write
us some Python code into C or C++ language and also we can compile that code in C/C++
language.
8. Dynamically Typed: Python is a dynamically-typed language. That means the type (for
example- int, double, long, etc.) for a variable is decided at run time not in advance because
of this feature we don’t need to specify the type of variable.
9. Platform Independent: 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.
10. Procedure as well as Object oriented
11. Large standard Library support: Python has a large standard library which provides a rich
set of module and functions so you do not have to write your own code for every single thing.
There are many libraries present in python for such as regular expressions, unit-testing, web
browsers, etc.
12. GUI Programming Support

1
LJIET Sem-5 PDS (3150713)

 Interpreter v/s Compiler:

Interpreter Compiler
It Translates program one statement at a time. Compiler scans the whole program in one go.
Considering it scans code one line at a time, As it scans the code in one go, the errors (if any)
errors are shown line by line. are shown at the end together.
It does not require source code for later
It requires source code for later execution.
execution.
It takes large amount of time to analyse the
It takes less amount of time to analyse the source
source code but the overall execution time is
code but the overall execution time is slower.
comparatively faster.
Example: Python, Ruby, Perl, etc. Example: C, C++ etc.

 C v/s Python :

C Python
C is a general-purpose, procedural computer Python is an interpreted, high-level, general-
programming language. purpose programming language.
It is easier to write a code in Python as the
Program syntax is harder than Python.
number of lines is less comparatively.
Python follows both the Procedure Oriented
C follows Imperative (Procedure Oriented)
as well as Object oriented Programming
programming paradigm.
paradigm.
C has a limited number of built-in functions. Python has a large library of built-in functions.
C programs runs faster than python program. Python code runs much slower than c.
Type Discipline is Static and Weak. Type Discipline is Dynamic and Strong.
It supports the concept of Switch Statement. It does not have Switch Statement.
It supports for, while and do…while loop. It supports only for and while loop.
Pointers are available in C. No pointers functionality available in Python.
No exception Handling. Supports Exceptional Handling mechanism.
Array Index can be positive as well as negative
Array Index Should be positive integer.
integer.
C uses traditional braces to start and end blocks. Python uses indentation to start and end blocks.
A semicolon (;) is used to terminate the
New Line (enter) indicates end of the statement.
statement.

2
LJIET Sem-5 PDS (3150713)

 Java v/s Python:


Java Python
Java is an Object Oriented Programming Python is a Procedure Oriented as well as Object
language. Oriented Programming language.
Java has a complex learning curve. Python is easy to learn and use.
Type Discipline is Static and Weak. Type Discipline is Dynamic and Strong.
Java code is bit lengthier than Python. Python code is shorter than JAVA.
Java is Statically typed. Python is Dynamically typed.
It supports the concept of Switch Statement. It does not have Switch Statement.
It supports for, for…each, while and do…while
It supports only for and while loop.
loop.
Array Index can be positive as well as negative
Array Index Should be positive integer.
integer.
Java uses traditional braces to start and end
Python uses indentation to start and end blocks.
blocks.
A semicolon (;) is used to terminate the
New Line (enter) indicates end of the statement.
statement.
Java is best for Desktop GUI apps, Embed Python is excellent for scientific and numeric
Systems, Web application services. computing as well as Machine learning apps.

 The Basic Elements of Python:


 Script: A Python program, sometimes called a script, is a sequence of definitions and
commands.
 Shell: Python Program definitions are evaluated and the commands are executed by the
Python interpreter in something called the shell.
 Statement: A command, often called a statement, instructs the interpreter to do
something.
 Objects: Objects are the core things that Python programs manipulate. Every object has a
type that defines the kinds of things that programs can do with objects of that type.
 Types of Objects:
1. Scalar: Scalar objects are indivisible. Think of them as the atoms of the language.
2. Non- Scalar: Non-scalar objects, for example strings, have internal structure.

 Python has 4 types of scalar objects: int, float, Bool, None

3
LJIET Sem-5 PDS (3150713)

 Variable:
 Variables provide a way to associate names with objects.
 In Python, variable names can contain uppercase and lowercase letters, digits (but they
cannot start with a digit), and the special character _.
 Python variable names are case-sensitive e.g., Julie and julie are different names.
 Finally, there are a small number of reserved words (sometimes called keywords) in Python
that have built-in meanings and cannot be used as variable names. Different versions of
Python have slightly different lists of reserved words.
 Example: a=5
 Python allows multiple assignment. The statement: x, y = 2, 3 works same as x=2 and y=3.

 Comments:
Text following the symbol # is not interpreted by Python.

For example:
# This is a single line comment.

“”” is used as multiple


line comment end with “””

‘’’ is also used as multiple line


comment end with ‘’’

 Built-In Data Types:


Built in Data types in python are of five types:
1. None Type:
The None data type represents an object that does not contain any value. In language like Java,
it is called ‘null’ object. But in python, it is called ‘None’ object. ‘None’ is that it is used inside
a function as a default value of the arguments. When calling a function if no value is passed
the default value will be taken as ‘None’.

2. Numeric Type:
 int: An integer number is a number without any decimal point or fraction part.
a= 15, b= -30, c=0
 float: float data type represents an floating point numbers. A floating number is a number
with decimal point or fraction part.
a= 55.679995; b= 22.55e3
 Complex: complex number is a number that is written in the form of “a+b j” or “a+b J”.
where ‘a’ is a real part and ‘b’ is an imaginary part.
a= - 1 – 5.5 j
 Bool: There are two Boolean values “True” and “False”. Python internally represents True
as 1 and false as 0. A blank string like “” is also represents as False.

4
LJIET Sem-5 PDS (3150713)

3. Sequences:
 str: str represents string data type. A string is a group of characters. Strings are enclosed in
single quotes or double quotes.
S1 = “Python”
S2=‘Java’

 Bytes: bytes data type represents a group of bye numbers just like an array does. The byte
number is any positive integer from 0 to 255.
elements= [10, 20, 30 40]
x = bytes (elements)
print (x[0]) # To print single element
for i in x: # To print all elements
print (i)

 Bytearray: bytearray data type represents a group of bye numbers just like an bytes does. But
the main difference is bytes type array cannot be modified but bytearray type array can be
modified.
elements= [10, 20, 30, 40]
x = bytearray(elements)
print (x[0]) # To print single element
for i in x: # To print all elements
print (i)
x[1] = 80 # Can modify values

 List: List is an ordered sequence of values, where each value is identified by an index. In
Python programming, a list is created by placing all the items (elements) inside a square
bracket [ ], separated by commas. It can have any number of items and they may be of different
types (integer, float, string etc.).
my_list = [1, 2, 3]
my_list = [1, "Hello", 3.4]

 Tuple: Like strings, tuples are ordered sequences of elements. The difference is that the
elements of a tuple need not be characters. The individual elements can be of any type, and
need not be of the same type as each other. In Python programming, a list is created by placing
all the items (elements) inside a round bracket ( ) , separated by commas. It can have any
number of items and they may be of different types (integer, float, string etc.). we cannot
change the elements of a tuple once it is assigned whereas in a list, elements can be changed.
my_tuple = (1, 2, 3)
my_tuple = (1, "Hello", 3.4)

 Range : returns a sequence of numbers, starting from 0 by default, and increments by 1 (by
default), and stops before a specified number..
r = range(10)
s = list(r)
print (s)

O/P: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

5
LJIET Sem-5 PDS (3150713)

4. Sets: A set is an unordered collection of elements. It means that the elements may not appear
in the same order as they are entered into set. Set does not accept duplicate elements.
S = {10, 20, 30, 40}

5. Mappings: a map represents a group of elements in the form of key and value pairs so that
when the key is given, we can retrieve the value associated with it. The dict (dictionary) data
type is an example of map.
my_dict = {1: 'apple', 2: 'ball'}

 Operators:
 Arithmetic Operator:

Operators Meaning Example


x = 15, y = 4
+ Add two operands or unary plus print ('x + y =', x+y)
# Output: x + y = 19
Subtract right operand from the left or print ('x - y =', x-y)
-
unary minus # Output: x - y = 11

print ('x * y =', x*y)


* Multiply two operands
# Output: x * y = 60

Divide left operand by the right one print ('x / y =', x/y)
/
(always results into float) # Output: x / y = 3.75

Modulus - remainder of the division of print ('x % y =', x%y)


%
left operand by the right # Output: x % y = 3
Floor division - division that results into
print ('x // y =', x//y)
// whole number adjusted to the left n the
# Output: x // y = 3
number line
Exponent - left operand raised to the print ('x ** y =', x**y)
**
power of right # Output: x ** y = 50625

 Logical Operator:
Operators Meaning Example
x = True, y = False
and True if both the operands are true print ('x and y is', x and y)
# Output: x and y is False
print('x or y is', x or y)
or True if either of the operands is true
# Output: x or y is True
True if operand is false (complements print('not x is', not x)
not
the operand) # Output: not x is False

6
LJIET Sem-5 PDS (3150713)

 Comparison Operator:

Operators Meaning Example


x = 10, y = 12
Greater than - True if left operand is print ('x > y is', x>y)
>
greater than the right
# Output: x > y is False
Less than - True if left operand is less print ('x < y is', x<y)
<
than the right # Output: x < y is True

Equal to - True if both operands are print ('x == y is', x==y)


==
equal # Output: x == y is False

Not equal to - True if operands are not print ('x != y is', x!=y)
!=
equal (always results into float) # Output: x != y is True
Greater than or equal to - True if left print ('x >= y is',x>=y)
>= operand is greater than or equal to the
# Output: x >= y is False
right
Less than or equal to - True if left print ('x <= y is',x<=y)
<=
operand is less than or equal to the right # Output: x <= y is True

 Assignment Operator:

Operators Meaning Equivalent to


= x=5 x=5
+= x += 5 x=x+5
-= x -= 5 x=x-5
*= x *= 5 x=x*5
/= x /= 5 x=x/5
%= x %= 5 x=x%5
//= x //= 5 x = x // 5
**= x **= 5 x = x ** 5

7
LJIET Sem-5 PDS (3150713)

 Bitwise Operator:

Operators Meaning Example


x = 10 (0000 1010 in binary)
& Bitwise AND y = 4 (0000 0100 in binary)
x& y = 0 (0000 0000)
| Bitwise OR x | y = 14 (0000 1110)

~ Bitwise NOT ~x = -11 (1111 0101)

^ Bitwise XOR x ^ y = 14 (0000 1110)

>> Bitwise right shift x>> 2 = 2 (0000 0010)

<< Bitwise left shift x<< 2 = 40 (0010 1000)

 Identity Operator:

Operators Meaning Example


x1 = 5
True if the operands are identical. (refer y1 = 5
is
to the same object) print(x1 is y1)
# Output: True
x1 = 5
True if the operands are not identical. (do y1 = 5
is not
not refer to the same object) print(x1 is not y1)
# Output: False

 Membership Operator:

Operators Meaning Exampl


e
x = 'Hello world'
Evaluates to true if it finds a variable in the
in print('H' in x)
specified sequence and false otherwise.
# Output: True
Evaluates to true if it does not find a x = 'Hello world'
not in variable in the specified sequence and false print(‘XYZ' not in x)
otherwise. # Output: True

8
LJIET Sem-5 PDS (3150713)

 Branching Program:

 The simplest branching statement is a conditional. As depicted in Figure, a conditional


statement has three parts:
 a test, i.e., an expression that evaluates to either True or False;
 a block of code that is executed if the test evaluates to True; and
 An optional block of code that is executed if the test evaluates to False.
 After a conditional statement is executed, execution resumes at the code following the
statement.

 In Python, a conditional statement has the form:


if Boolean expression:
block of code
else:
block of code

 if…elif…else Statement Syntax:


if test expression:
Body of if
elif test expression:
Body of elif
else:
Body of else

 Nested if Statement Syntax:


if test expression:
Body of if
if test expression:
block of code
else:
block of code
else:
Body of else

9
LJIET Sem-5 PDS (3150713)

 Examples of if else:
 If Statement:
temp = 20
if temp > 10 :
print ("It is cold!)

 If else Statement:
temp = 20
if temp > 10 :
print ("It is cold!)
else:
print ("It feels good!)

 Chained Condition (if.., elif.., else):


temp = 20
if temp < 10 :
print "It is cold!"
elif temp > 30:
print "It is hot!"
else:
print "It feels good!”

 Nested Condition:
if num%2==0:
if num%3==0:
print ("Divisible by 3 and 2")
else:
print ("divisible by 2 not divisible by 3")
else:
if num%3==0:
print ("divisible by 3 not divisible by 2")
else:
print ("not Divisible by 2 not divisible by 3")

10
LJIET Sem-5 PDS (3150713)

 Iteration:

 A generic iteration (also called looping) mechanism is depicted in Figure. Like a conditional
statement it begins with a test. If the test evaluates to True, the program executes the loop
body once, and then goes back to revaluate the test.
 This process is repeated until the test evaluates to False, after which control passes to the code
following the iteration statement.

 For Loop:  While Loop:


for val in sequence: while test expression:
Body of for Body of while
else: else:
Body of else Body of else

 Example:  Example:
counter = 0
digits = [0, 1, 5]
while counter < 3:
for i in digits:
print ("Counter: ", counter)
print (i)
counter = counter + 1
else:
else:
print ("No items left.")
print ("Inside Else.")

 Output:  Output:
0 Counter: 0
1 Counter: 1
5 Counter: 2
No items left. Inside Else.

11
LJIET Sem-5 PDS (3150713)

 Control Structure:
 There are mainly three type of control structure in python:
 BREAK: The break statement terminates the loop containing it. Control of the program flows
to the statement immediately after the body of the loop.
for letter in 'Python':
if letter == 't':
break
print ('Current Letter :', letter)

Output:
Current Letter: P
Current Letter: y

 CONTINUE: The continue statement rejects all the remaining statements in the current
iteration of the loop and moves the control back to the top of the loop.
for letter in 'Python':
if letter == 'h':
continue
print 'Current Letter :', letter

Output:
Current Letter: P
Current Letter: y
Current Letter: t
Current Letter: o
Current Letter: n

 PASS: The pass statement is a null operation; nothing happens when it executes. The pass is
also useful in places where your code will eventually go, but has not been written yet
for letter in 'Python':
if letter == 'h':
pass
print 'This is pass block' print
'Current Letter :', letter

Output:
Current Letter: P
Current Letter: y
Current Letter: t
This is pass block
Current Letter: h
Current Letter: o
Current Letter: n

12
LJIET Sem-5 PDS (3150713)

 Function:
 Function is a group of related statements that perform a specific task.
 Functions help break our program into smaller and modular chunks. As our program grows
larger and larger, functions make it more organized and manageable.
 The ability for programmers to define and then use their own functions, as if they were built-
in, is a qualitative leap forward in convenience.
 Syntax:
def name of function (list of formal parameters):
body of function
 def is a reserved word that tells Python that a function is about to be defined.
 Example:
def greet(name):
print("Hello, " + name + ". Good morning!")
#Function Call
greet('World')

 Output:
Hello, World. Good morning!

 Types of function arguments :


1. Python Positional Arguments: These are the arguments passed to a function in correct
positional order. The number of arguments and their positions in the function definition should
match exactly with the number and position of the argument in the function call.

Example: Output:
def demo(name, age): Name: Python
print (“Name: “,name) Age: 20
print (“Age: “,age)

demo (“Python”,20)

2. Python Keyword Arguments: A keyword argument is where you provide a name to the
variable as you pass it into the function. When we call functions in this way, the order
(position) of the arguments can be changed. we can mix positional arguments with keyword
arguments during a function call. But we must keep in mind that keyword arguments must
follow positional arguments. Having a positional argument after keyword arguments will
result into errors.

Example: Output:
def demo(name, age): Name: Python
print (“Name: “,name) Age: 25
print (“Age: “,age)
demo (age =25, name=“Python”)

13
LJIET Sem-5 PDS (3150713)

3. Python Default Arguments: Function arguments can have default values in Python. We can
provide a default value to an argument by using the assignment operator (=). Any number of
arguments in a function can have a default value. But once we have a default argument, all
the arguments to its right must also have default values. This means to say, non-default
arguments cannot follow default arguments.

Example: Output:
def demo(name, age=20): Name: Python
print (“Name: “,name) Age: 20
print (“Age: “,age)

demo (“Python”)

4. Python Arbitrary Arguments: Sometimes, we do not know in advance the number of


arguments that will be passed into a function. Python allows us to handle this kind of situation
through function calls with arbitrary number of arguments. In the function definition we use
an asterisk (*) before the parameter name to denote this kind of argument. Here is an example.

Example: Output:
def demo(*name): Name: Python
for i in name: Name: Java
print (“Name: “,i) Name: AI
Name: ML
demo (“Python”, “Java”, “AI”, “ML”)

 Lambda:
 A lambda function is a small anonymous function. A lambda function can take any number
of arguments, but can only have one expression.
 Syntax:
lambda argument_list : expression

Without Lambda: With Lambda:


def square(x): f = lambda x : x * x
return x * x print(‘square of 5=’, f(5))
y= square(5)

Output: Output:
25 square of 5 = 25

14
LJIET Sem-5 PDS (3150713)

 Map: The map() function acts on each element of the sequence and perhaps changes the
elements.
Syntax: map( function, sequence)

Example:
def squares(x):
return x*x
lst=[1,2,3,4,5]
lst1=list(map(squares,lst))
print (lst1)
Output: [1, 4, 9, 16, 25]

 Filter: The filter() function is useful to filter out the elements of a sequence depending on
the result of a function.
Syntax: filter (function, sequence)

Example:
def is_even(x):
if x%2==0:
return True
else:
return False
lst= [10, 23, 45, 46, 79, 99]
lst1= list(filter(is_even,lst))
print (lst1)
Output: [10, 46]

 Reduce: The reduce() function reduces a sequences of elements to a single value by


processing the elements according to a function supplied.
Syntax:
reduce (function, sequence)
Example:
from functools import *
lst = [1, 2, 3, 4, 5]
result = reduce(lambda x,y:x*y, lst)
print (result)
Output: 120

15
LJIET Sem-5 PDS (3150713)

 Scope and Lifetime of variables:


 Scope of a variable is the portion of a program where the variable is recognized. Parameters
and variables defined inside a function is not visible from outside. Hence, they have a local
scope.
 Lifetime of a variable is the period throughout which the variable exits in the memory. The
lifetime of variables inside a function is as long as the function executes.
 They are destroyed once we return from the function. Hence, a function does not remember
the value of a variable from its previous calls.
 Here is an example to illustrate the scope of a variable inside a function.
var = 100
def my_func():
var = 10
print("Local Value inside function:",var)

print("Globle Value outside function:",var)


my_func()

Output:
Globle Value outside function: 100
Local Value inside function: 10

 If you want to access global variable inside the function then you have to use global
keyword
var = 100
# this function will not give error
def my_func():
global var
var = var + 10
print (“Value inside function:",var)
my_func()
print (“Value outside function:",var)

Output:
Value inside function: 110
Value outside function: 110

 It is important to note that though the actual and formal parameters have the same name,
they are not the same variable. Each function defines a new name space, also called a
scope.

16
LJIET Sem-5 PDS (3150713)

 Specification:
 A specification of a function defines a contract between the implementer of a function and
those who will be writing programs that use the function. We will refer to the users of a
function as its clients. This contract can be thought of as containing two parts:
1. Assumptions: These describe conditions that must be met by clients of the function.
Typically, they describe constraints on the actual parameters. Almost always, they specify the
acceptable set of types for each parameter, and not infrequently some constraints on the value
of one or more of the parameters.
2. Guarantees: These describe conditions that must be met by the function, provided that it has
been called in a way that satisfies the assumptions.

 Example:
def fact(n) :
"""Assumes that n is an int > 0
Returns n!"""
result = 1
while n > 1 :
result = result * n
n -= 1
return result

 The text between the triple quotation marks is called a doctoring in Python. By convention,
Python programmers use docstrings to provide specifications of functions. These docstrings
can be accessed using the built-in function help().
 docstrings can also be accessed using: Function-Name.__doc__

 Example:
print (fact.__doc__)

17
LJIET Sem-5 PDS (3150713)

 Modules:
 A module represents a group of classes, methods, functions and variables. When a module is
developed, it can be reused in any program that needs that module.
 In python we have several in built modules like sys, io, time etc. just like this modules, we
can also create our own modules and use them whenever we need them.
 Python modules allow us to easily construct a program from code in multiple files. A module
is a .py file containing Python definitions and statements. We could create, for example, a file
circle.py containing.
 Example:
circle.py file:
pi = 3.14159
def area(radius):
return pi*(radius**2)
def circumference(radius):
return 2*pi*radius
def sphereSurface(radius):
return 4.0*area(radius)

circle_run.py file:
import circle import circle as c
print (circle.pi) print (c.pi)
print (circle.area(3)) print (c.area(3))
print (circle.circumference(3)) print (c.circumference(3))

 Output:
3.14159
28.27431
18.849539999999998

 Executing import M creates a binding for module M in the scope in which the
importation occurs. Therefore, in the importing context we use dot notation to indicate that
we are referring to a name defined in the imported module.
 For example, outside of circle.py, the references pi and circle.pi can (and in this case do) refer
to different objects.
 There is a variant of the import statement that allows the importing program to omit the
module name when accessing names defined inside the imported module. Executing the
statement from M import * creates bindings in the current scope to all objects defined within
M, but not to M itself.
 For example, the code
from circle import *

18
LJIET Sem-5 PDS (3150713)

 Recursion:
 Recursion is the process of defining something in terms of itself. In simple words, it is a
process in which a function calls itself directly or indirectly.
 Recursion is a method of solving a problem where the solution depends on solutions to smaller
instances of the same problem.

 Advantages:
 A complicated function can be split down into smaller sub-problems utilizing recursion.
 Sequence creation is simpler through recursion than utilizing any nested iteration.
 Recursive functions render the code look simple and effective.

 Disadvantages:
 A lot of memory and time is taken through recursive calls which makes it expensive for use.
 Recursive functions are challenging to debug.
 The reasoning behind recursion can sometimes be tough to think through.

 Example: (Factorial)
def calc_factorial(x):
"""This is a recursive function
to find the factorial of an integer"""
if x == 1:
return 1
else:
return (x * calc_factorial(x-1))

num = int(input(“Enter No: “))


print ("The factorial of", num, "is", calc_factorial(num))

 Output:
Enter No: 4
The factorial of 4 is 24

19
LJIET Sem-5 PDS (3150713)

 String:

 String represents a group of characters. To create a string in python, assign a group of


characters to a variable, should be enclosed inside single quotes or double quotes:
Str1= ‘hello world’
Str2= “hello world”
 Also we can use triple single quotes or triple double quotes while creating the string to
represent a string that occupies several lines:
Str3= ‘’’hello
World’’’
Str4= “””hello
World”””
 To display substring inside string:
Str5= ‘I am “python” program’
Str6= “I am ‘python’ program”
 To print a string: print (Str1)

 Indexing in String:
 Index represents the position number. They are written using square braces [ ]. By specifying
the index we can refer individual elements.
 String[i] represents ith element of string. Positive index starts from left to right and negative
index starts from right to left (end of the string).

 Slicing in String:
Slice represents a part or piece of a string.
Syntax: string_name [ start : stop : step_size ]

 Example:
S1='core python'
print (S1 [0:9:1]) #accessing string from 0th to 8th element in steps of 1
print (S1[::]) #access string from start to last character
print (S1 [2:6:1]) #accessing strting from S1[2] to S1[5] element in steps of 1
print (str[::2]) #accessing entire strting in steps of 2
print (S1[::-1]) #reverse the string

 Output:
core pyth
core python
re p

20
LJIET Sem-5 PDS (3150713)

cr yhn
nohtyp eroc
 Repeating in String:
str='core python'
print (str*2)
s=str[5:7]*3
print(s)

Output:
core pythoncore python
pypypy

 Concatenation of String:
str1='core python'
str2="programs"
str3=str1+str2
print (str3)

Output: core pythonprograms

 Checking membership of String:


str1="this is a string"
sub="is"
if sub in str1:
print ("sub string is found in main string")
else:
print ("sub string is not found in main string")

Output: sub string is found in main string

 Comparing String:
str1="Box"
str2="box"
if(str1==str2):
print ("Both are same")
else:
print ("Both are not same")

Output: Both are not same

21
LJIET Sem-5 PDS (3150713)

Method Description
len() Returns the length of string
count() Returns the number of times a specified value occurs in a string
upper() Converts a string into upper case
lower() Converts a string into lower case
swapcase() Swaps cases, lower case becomes upper case and vice versa
title() Converts the first character of each word to upper case
Returns the string whose first letter is capital and remaining are
capitalize()
lowercase
startswith() Returns true if the string starts with the specified value
endswith() Returns true if the string ends with the specified value
rstrip() Returns a right trim version of the string
lstrip() Returns a left trim version of the string
strip() Returns a trimmed version of the string
isalnum() Returns True if all characters in the string are alphanumeric
isalpha() Returns True if all characters in the string are in the alphabet
isdigit() Returns True if all characters in the string are digits
islower() Returns True if all characters in the string are lower case
isupper() Returns True if all characters in the string are upper case
istitle() Returns True if the string follows the rules of a title
isspace() Returns True if all characters in the string are whitespaces
Searches the string for a specified value and returns the position of where
find()
it was found
Searches the string for a specified value and returns the last position of
rfind()
where it was found
Searches the string for a specified value and returns the position of where
index()
it was found
Searches the string for a specified value and returns the last position of
rindex()
where it was found
Returns a string where a specified value is replaced with a specified
replace()
value
split() Splits the string at the specified separator, and returns a list
join() Joins the elements of an iterable to the end of the string

22
LJIET Sem-5 PDS (3150713)

 Example:
#Changing case of a string:
str1="pYthon pRograMming is a fun" Output:
print("String: ",str1) String: pYthon pRograMming is a fun
print ("Upper: ",str1.upper()) Upper: PYTHON PROGRAMMING IS A FUN
print ("Lower: ",str1.lower()) Lower: python programming is a fun
print ("Swapcase: ",str1.swapcase()) Swapcase: PyTHON PrOGRAmMING IS A FUN
print ("Title: ",str1.title()) Title: Python Programming Is A Fun
print ("Capitalize: ",str1.capitalize()) Capitalize: Python programming is a fun

#Checking Starting and Ending of a string:


str1="This is python" Output:
print (str1.startswith('This')) True
print (str1.endswith('python')) True
print (str1.endswith('N')) False

#String Testing Methods:


demoStr="GTU2021" Output:
print ("isalnum: ", demoStr.isalnum()) isalnum: True
print ("isalpha: ", demoStr.isalpha()) isalpha: False
print ("isdigit:", demoStr.isdigit()) isdigit: False
print ("islower:", demoStr.islower()) islower: False
print ("isupper:",demoStr.isupper()) isupper: True
print ("istitle:",demoStr.istitle()) istitle: False
print ("isspace:",demoStr.isspace()) isspace: False

#Split() of string:
str1= "One, Two, Three, Four" Output:
str2= str1.split(',') ['One', ' Two', ' Three', ' Four']
print (str2)

#join() of string:
str1=('one','two','three') Output:
str2='-'.join(str1) one-two-three
print (str2)

23
LJIET Sem-5 PDS (3150713)

 List:
 List in Python can be written as a list of comma-separated values (items) between square
brackets.
 List items are ordered, Mutable (changeable), and allow duplicate values.
 Syntax for creating an empty list: list1 = []
 List storing string data: List2 = [‘Python’ , ’Data Science’]
 List storing heterogeneous data: List2 = [‘Hello World’ ,1,2.50,5+10j]

Method Description
len() Return the length (the number of items) in the list.
list() Convert an iterable (tuple, string, set, dictionary) to a list.
copy() Returns a shallow copy of the list
index() Returns the index of the first matched item
count() Returns the count of occurrence of item passed as an argument
insert() Insert an item at the defined index
append() Add an element to the end of the list
extend() Add all elements of a list to the another list
remove() Removes an item from the list
pop() Removes and returns an element at the given index
clear() Removes all items from the list
del() Delete an item at particular index
sort() Sort items in a list in ascending order
reverse() Reverse the order of items in the list
min() Return the smallest item in the list.
max() Return the largest item in the list.
sorted() Return a new sorted list (does not sort the original list).
sum() Return the sum of all elements in the list.
all() Return True if all elements of the list are true (or if the list is empty).
Return True if any element of the list is true. If the list is empty, return
any()
False.
Return an enumerate object. It contains the index and value of all the
enumerate()
items of list as a tuple.

24
LJIET Sem-5 PDS (3150713)

 Example:
# List with mixed DataTypes Output:
my_list = [1, "Hello", 3.4] [1, 'Hello', 3.4]
print(my_list)

# Nested List Output:


my_list = ["mouse", [8, 4, 6], ['a']] ['mouse', [8, 4, 6], ['a']]
print(my_list)

#Indexing Output:
my_list = ['l','j','i','e','t','s','g','h','y'] l
print(my_list[0]) i
print(my_list[2]) t
print(my_list[4])

#Negative Indexing Output:


my_list = ['l','j','i','e','t','s','g','h','y'] y
print(my_list[-1]) t
print(my_list[-5])

#Nested Indexing Output:


n_list = [[1,2],"ABCDEF",[4,5,6],10] 2
print(n_list[0][1]) D
print(n_list[1][3])

#Slicing Output:
my_list = ['l','j','i','e','t','s','g','h','y'] ['i', 't']
print(my_list[2:5:2]) ['l', 'j', 'i', 'e']
print(my_list[:-5]) ['s', 'g', 'h', 'y']
print(my_list[5:]) ['y', 'h', 'g', 's', 't', 'e', 'i', 'j', 'l']
print(my_list[::-1])

#Change Element of List Output:


odd = [2, 4, 6, 8,10,12] [10.25, 4, 6, 8, 10, 12]
odd[0] = 10.25 [10.25, 3, 5, 7, 10, 12]
print(odd)
odd[1:4] = [3, 5, 7]
print(odd)

#Concatenation Output:
odd = [2, 4, 6, 8] [2, 4, 6, 8]
print(odd) + operator to combine two lists
print("+ operator to combine two lists") [2, 4, 6, 8, 9, 7, 5]
print(odd + [9, 7, 5])

25
LJIET Sem-5 PDS (3150713)

#Repetition of List: Output:


odd = [2, 4, 6, 8] [2, 4, 6, 8]
print(odd) * operator repeats a list for the given number of times.
print("* operator repeats a list for the [2, 4, 6, 8, 2, 4, 6, 8, 2, 4, 6, 8]
given number of times.")
print(odd * 3)

#Delete Element of List


odd = [1, 3, 20, 4, 6, 8]
print("delete element of list")
del odd[2]
print(odd)
odd = [1, 3, 20, 4, 6, 8]
del odd[0:]
print(odd)
odd = [2, 4, 6, 8]
del odd
print(odd)

#Creating list using range() : We can use the range() to generate a sequence of integers which
#can be stored in a list.
lst=list(range(4,9,2))
print(lst)

#List Membership Test:


my_list = ['p','r','o','b','l','e','m']
s='p'
print(s in ['p','r','o','b','l','e','m'])
print('a' in my_list)
print('c' not in my_list)

#Iterating Through a List


s=['apple','banana','mango']
for fruit in s:
print("I like",fruit)

#append() : Add an element to the end of the list


lst=[0,1,2,3,4,5,6]
print ('Original: ',lst)
lst.append('hi') #add new element
print (lst)

26
LJIET Sem-5 PDS (3150713)

#extend(): Add all elements of a list to the another list


lst=[0,1,2,3,4,5,6]
lst.extend([3,6,8]) #add Multiple elements
print (lst)

#insert(): Insert an item at the defined index


lst=[0,1,2,3,4,5,6]
lst.insert(5,'hello') #inserting element at particular index
print (lst)

#remove(): Removes an item from the list


lst=[0,1,2,3,4,15,6]
lst.remove(15) #removing by element
print (lst)

#del(): Delete an item at particular index


lst=[0,1,2,3,4,5,6]
del lst[2] #removing by index
print (lst)

#pop(): Removes and returns an element at the given index


lst=[0,1,2,3,4,15,6]
print (lst.pop(5))

##Index(): Returns the index of the first matched item


lst=[0,1,2,3,'hi',5,6,4]
print (lst.index('hi'))

#count(): Returns the count of number of items passed as an argument


lst=[1,2,3,4,4,4]
print (lst.count(4))

#sort(): Sort items in a list in ascending order


lst1=[3,1,7,4,2]
lst1.sort()
print (lst1)
lst1.sort(reverse=True)
print (lst1)

#sorted():Return a new sorted list (does not sort the list itself).
lst1=[3,6,2,1,25,69,9,1]
print(lst1)
print (sorted(lst1,reverse=True))#lst1.sort()
print (lst1)

27
LJIET Sem-5 PDS (3150713)

#reverse(): Reverse the order of items in the list


lst=[0,1,2,3,4,5,6,2,22,12]
lst.reverse()
print (lst)

'''Built-in Functions with List'''


#all():Return True if all elements of the list are true (or if the list is empty).
lst1=[0,1,2,3,4,5,6]; lst2=[1,2,3]
print (all(lst1), all(lst2))

#any():Return True if any element of the list is true. If the list is empty, return False.
lst1=[0,1,2,3,4,5,6]; lst2=[0,0,0]
print (any(lst1), any(lst2))

#enumerate(): Return an enumerate object. It contains the index and value of all the items of
#list as a tuple
lst1=[11,12,30,4]
print (enumerate(lst1))
print (list(enumerate(lst1)))

#len(): Return the length (the number of items) in the list.


lst1=[1,2,3,4]
print (len(lst1))

#list(): Convert an iterable (tuple, string, set, dictionary) to a list.


set1={1,2,3,4}
print (list(set1))

#max(): Return the largest item in the list.


lst1=[1,2,3,4]
print (max(lst1))

#min(): Return the smallest item in the list.


lst1=[1,2,3,4]
print (min(lst1))

#sum():Return the sum of all elements in the list.


lst=[1,2,3,4,4,4]
print (sum(lst))

28
LJIET Sem-5 PDS (3150713)

 Tuple:

 Tuple in Python can be written as a list of comma-separated values (items) between


parentheses.
 A tuple is a collection which is Ordered and Immutable.
 Tuple also allows duplicate elements.
 Syntax for creating an empty tuple: tup = ()
 Tuple storing string data: tup1 = (‘Python’ , ’Data Science’)
 Tuple storing heterogeneous data: tup2 = (‘Hello World’ ,1,2.50,5+10j)

Method Description
len() Return the length (the number of items) in the list.
list() Convert an iterable object to a tuple.
index() Returns the index of the first matched item
count() Returns the count of occurrence of item passed as an argument
min() Return the smallest item in the list.
max() Return the largest item in the list.
sorted() Return a new sorted list (does not sort the original list).

 Example:
#Tuple Declaration
t1=()
t2=(1, 'two', 3, 2.5)
t3=(12,) #singletone element
print (t1)
print (t2)
print (t3)

#Tuples can be Concatenated, Indexed, and Sliced


t1 = (1, 'two', 3)
t2 = (t1, 3.25)
print (t2[0][1])
t2=(3.25,'Py','Gtu')
print (t1 + t2)
print ((t1 + t2)[3])
print ((t1 + t2)[2:5])

29
LJIET Sem-5 PDS (3150713)

###Accessing tuple elements


tup=(2,3,4,5,6,7,8,9)
print (tup)
print (tup[:]) # (2,3,4,5,6,7,8,9)
print (tup[0]) #2
print (tup[1:6]) # (3,4,5,6,7)
print (tup[-4]) # 6
print (tup[1::3]) # (3,6,9)

student =(10,'Python',20,30,40)
print (student[0:2])
rno, name = student[0:2]
print (rno)
print (name)

'''Built-in Functions and method with Tuple'''

#len(): Return the length (the number of items) in the tuple.


tup1=(1,2,3,4)
print (len(tup1))

#max(): Return the largest item in the tuple.


tup1=(1,2,3,4)
print (max(tup1))

#min(): Return the smallest item in the tuple.


tup1=(1,2,3,4)
print (min(tup1))

#index(): Returns the index of the first matched item


tup1=(1,2,3,4,'hi')
print (tup1.index(4))

#count(): Returns the count of number of items passed as an argument


tup1=(1,2,3,4,4,4)
print (tup1.count(4))

#sorted(): Return a new ascending sorted tuple (does not sort the tuple itself),
#sorted(tup,reverse=True) will sort in reverse order.
tup1=(3,6,2,1)
print (sorted(tup1))
print (sorted(tup1,reverse=True))

30
LJIET Sem-5 PDS (3150713)

#Nested tuple
emp=((90,'Ram',30000),(52,'Shyam',25000),(64,'Krishna',35000))
print (emp)
print (emp[1][1])
print (sorted(emp))
print (sorted(emp,reverse=True))
print (sorted(emp,key=lambda x:x[1])) #sort on name
print (sorted(emp,key=lambda x:x[2])) #sort on salary

''' Tuples and Immutability '''

#Inserting Element into a tuple at specific position


num=(1,2,3,4,6,7,8)
print (num)
lst=[int(input('Enter a new number:'))]
new=tuple(lst)
i=int(input('Enter index no:'))#2
num1=num[0:i] #1,2,55,3,4
num1=num1+new
num=num1+num[i:]
print (num)

#Modifying Element of a tuple at specific position


num=(1,2,3,4)
print (num)
lst=[int(input('Enter a new number:'))]
new=tuple(lst)
i=int(input('Enter index no:'))
num1=num[0:i]
num1=num1+new
num=num1+num[i+1:]
print (num)

#Deleting Element from a tuple at specific position


num=(1,2,3,4)
print (num)
i=int(input('Enter index no:'))
num1=num[0:i]
num=num1+num[i+1:]
print (num)

31
LJIET Sem-5 PDS (3150713)

 Dictionary:
 Dictionary in Python is an ordered collection of data values, used to store data values like a
map, which, unlike other Data Types that hold only a single value as an element, Dictionary
holds key:value pair. Key-value is provided in the dictionary to make it more optimized.
 In Python, a Dictionary can be created by placing a sequence of elements within curly {}
braces, separated by ‘comma’.
 Dictionary holds a pair of values, one being the Key and the other corresponding pair element
being its Key:value.

Method Description
len() Return the length (the number of items) in the dictionary.
clear() Removes all the elements from the dictionary
fromkeys() Returns a dictionary with the specified keys and value
get() Returns the value of the specified key
items() Returns a list containing a tuple for each key value pair
keys() Returns a list containing the dictionary's keys
values() Returns a list of all the values in the dictionary
pop() Removes the element with the specified key
popitem() Removes the last inserted key-value pair
Returns the value of the specified key. If the key does not exist:
setdefault()
insert the key, with the specified value
update() Updates the dictionary with the specified key-value pairs
Return True if all keys of the dictionary are true (or if the dictionary
all()
is empty).
Return True if any key of the dictionary is true. If the dictionary is
any()
empty, return False.
sorted() Return a new sorted list of keys in the dictionary.

 Converting strings into Dictionary:


str1 = "Python=10,AI=20, ML=30"
lst=[]
for x in str1.split(','):
y=x.split('=')
lst.append(y)
d=dict(lst)
print (d)

 Output:
{'ML': '30', 'Python': '10', 'AI': '20'}

32
LJIET Sem-5 PDS (3150713)

 Example:
#Dictionary Declaration
print("Displaying Dictionary")
my_dict = {}
my_dict = {1: 'apple', 2: 'ball'}
print(my_dict)
my_dict = {'name': 'John', 1: [2, 4, 3]}
print(my_dict)
my_dict = dict([(1,'apple'), (2,'ball')])
print(my_dict)

my_dict = {'name':'Jack', 'age': 26}


print(my_dict)
print(my_dict['name'])

#Change Element of Dictionary


my_dict['age'] = 27
print(my_dict)

#Add element to Dictionary


my_dict = {'name':'Jack', 'age': 26}
my_dict[10] = 'Downtown'
print(my_dict)

#Delete element from Dictionary


my_dict = {'name':'Jack', 'age': 26}
del my_dict['age']
print(my_dict)

# fromkey method: Return a new dictionary with keys from seq and value
marks = {}.fromkeys(['Math','English','Science'], 0)
print(marks)
for item in marks.items():
print(item)
print(list(sorted(marks.keys())))

#Dictionary Membership Test


squares = {1: 10, 2: 24, 's': 25, 'k': 49}
print(1 in squares)
print(49 in squares)

33
LJIET Sem-5 PDS (3150713)

#Iterating Through a Dictionary


squares = {1: 1, 3: 9, 5: 25, 7: 49, 9: 81}
for i in squares:
print('Key: ',i)
print('Values: ',squares[i])

'''Dictionary Inbuilt Methods'''


#clear(): Remove all items form the dictionary.
d={1:'Python',2:'Java'}
d.clear()
print (d)

#copy(): Return a shallow copy of the dictionary.


d={1:'Python',2:'Java'}
d1=d.copy()
print (d1)

#get(key[,d]): Return the value of key. If key does not exit, return d (defaults to None).
d={1:'Python',2:'Java'}
d[10]="Bye"
print (d.get(1,'none'))
print (d.get(3,'Key not exist'))

#items():Return a new view of the dictionary's items (key, value).


d={1:'Python',2:'Java'}
print (d.items())
print (d1.keys())#keys(): Return a new view of the dictionary's keys.
print (d1.values())#values(): Return a new view of the dictionary's values.

#pop(key[,d]): Remove the item with key and return its value or d if key is not found.
#If d is not provided and, raises KeyError
d={1:'Python',2:'Java',3:'AI'}
print (d.pop(1,'Not Present'))
print (d.pop(30,'Not Present'))

#popitem(): Remove and return an arbitrary item (key, value).


#Raises KeyError if the dictionary is empty.
d={1:'Python',2:'Java',3:'AI'}
print (d.popitem())

34
LJIET Sem-5 PDS (3150713)

#setdefault(key[,d]): If key is in the dictionary, return its value.


#If not, insert key with a value of d and return d (defaults to None).
d={1:'Python',2:'Java'}
print (d.setdefault(2,0))
print (d.setdefault(3,'AI'))
print (d)

#update([other]): Update the dictionary with the key/value pairs from other,
#overwriting existing keys
d={1:'Python',2:'Java',3:'AI'}
ud={3:'ML',4:'AI'}
d.update(ud)
print (d)
d.update({5:'AI++'})
print (d)

''' Built-in Functions with Dictionary '''


#all(): Return True if all keys of the dictionary are true (or if the dictionary is empty).
d={1:'Python',2:'Java',3:'AI'}
print (all(d))
D={}
print (all(D))

#any(): Return True if any key of the dictionary is true.


#If the dictionary is empty, return False.
d={1:'Python',2:'Java',3:'AI'}
print (any(d))

#len(): Return the length (the number of items) in the dictionary.


d={1:'Python',2:'Java',3:'AI'}
print (len(d))

#sorted(): Return a new sorted list of keys in the dictionary.


colors={10:'red',35:'green',15:'blue',25:'white'}
# sorting of list by key in ascending order
print (sorted(colors.items(), key=lambda x:x[0]))
# sorting of list by key in descending order
print (sorted(colors.items(), reverse=True, key=lambda x:x[0]))
# sorting of list by value in descending order
Print (sorted(colors.items(), reverse=True, key=lambda x:x[1]))

35
LJIET Sem-5 PDS (3150713)

 Set:
 Set items are unordered, mutable (changeable), and do not allow duplicate values.
 We can create set using curly brackets.
 We cannot access items in a set by referring to an index as sets are unordered the items has
no index.
 Syntax for creating an empty set:
s1 = {}
s1=set()

 Example:
s={1,2,3,4}
print ("set: ",s)
O/P: set: {1,2,3,4}

#Accessing set item


s={1,2,3,4}
for i in s:
print('Item: ',i)
O/P:
Item: 1
Item: 2
Item: 3
Item: 4

#Membership Operator
s={1,2,3,4} O/P:
print ("set: ",s) set: {1, 2, 3, 4}
print ("1 in Set: ",1 in s) 1 in Set: True
print ("9 in Set: ",9 in s) 9 in Set: False

#Updating set element


s={1,2,3,4} O/P:
print ("set: ",s) set: {1, 2, 3, 4}
s.add(5) #for adding single element Updated Element: {1, 2, 3, 4, 5}
print ("Updated Element: ",s) Updated Element: {1, 2, 3, 4, 5, 7, 8, 9}
s.update([7,8,9]) #for adding more than one
element at a time
print ("Updated Element: ",s)

36
LJIET Sem-5 PDS (3150713)

 Operations that are not supported by Set Data Structure in Python

#Concatenation Operator (*)


s1={1,2,3,4}
s2={"Hello", "World"}
print ("After Concatenations: ", s1+s2) #Error because concatenation is not allowed
O/P:
TypeError: unsupported operand type(s) for +: 'set' and 'set'

#Repetition Operator (*)


s={1,2,3,4}
print ("set: ",s)
print ("After Repetition: ",s*2)
O/P:
unsupported operand type(s) for *: 'set' and 'int'

#Slice Operation
s={1,2,3,4,5}
print ("set: ",s)
print ("After Slicing: ",s[2])
O/P:
TypeError: 'set' object is not subscriptable

 Built in Methods of Set


#union(): Returns a set that contains all items from the original set, and all items
# from the specified set(s).
x={1,2,3,4,5} O/P:
y={1,7,8,9} original set X: {1, 2, 3, 4, 5}
print("original set X:",x) original set Y: {8, 1, 9, 7}
print("original set Y:",y) Union: {1, 2, 3, 4, 5, 7, 8, 9}
print ("Union:", x.union(y))

#intersection(): Returns a set that contains the similarity between two Sets.
x={1,2,3,4,5} O/P:
y={1,3,5} original set X: {1, 2, 3, 4, 5}
print("original set X:",x) original set Y: {1, 3, 5}
print("original set Y:",y) Intersection: {1, 3, 5}
print("Intersection:",x.intersection(y))

37
LJIET Sem-5 PDS (3150713)

# difference(): Return a set that contains the items that only exist in set x, and
not in set y, it does not change the original set x or y.
x = {1,2,3,4} O/P:
y = {1,3} original set X: {1, 2, 3, 4}
print("original set X:",x) original set Y: {1, 3}
print("original set Y:",y) Difference: {2, 4}
print("Difference: ",x.difference(y))

# difference_update(): Removes the items that are common in both the set from
the original Set. It returns none and updates the original set
x = {1,2,3,4} O/P:
y = {1,3} original set X: {1, 2, 3, 4}
print("original set X:",x) original set Y: {1, 3}
None
print("original set Y:",y)
Difference: {2, 4}
print(x.difference_update(y))
print("Difference: ",x)

# copy(): Returns a Copy of a Set


x={1,2,3,4,5} O/P:
y=x.copy() #Shallow copy set x: {1, 2, 3, 4, 5}
print("set x:", x) set y: {1, 2, 3, 4, 5}
print("set y:", y)

# remove(): Removes the specified element from the Set


x={1,2,3,4} O/P:
print("Original set X:",x) Original set X: {1, 2, 3, 4}
x.remove(2) Updated set x: {1, 3, 4}
print("Updated set x:",x)

# discard(): Removes the specified item from the Set.


x = {"A", "B", "C"} O/P:
print("original set X:",x) original set X: {'C', 'B', 'A'}
x.discard("B") Updated set x: {'C', 'A'}
print("Updated set x:",x)

# pop(): Removes a random item from the Set.


x={1,2,3,4,5} O/P:
print("original set X:",x) original set X: {1, 2, 3, 4, 5}
print(x.pop()) 1
print("Updated set x:",x) Updated set x: {2, 3, 4, 5}

38
LJIET Sem-5 PDS (3150713)

# del: Delete the Set completely


x={1,2,3,4,5} O/P:
del x NameError: name 'x' is not defined
print("After Deleting:",x)

# Clear(): Removes all elements of Set


x={1,2,3,4,5} O/P:
print("set: ",x) set: {1, 2, 3, 4, 5}
x.clear() After Clearning: set()
print ("After Clearing:",x)

# issubset(): Returns True If all items in the set exists in the specified set, Else it
returns False
x={1,2,3,4,5} O/P:
y={1,3,5} X issubset Y: False
print("X issubset Y:",x.issubset(y)) Y issubset X: True
print("Y issubset X:",y.issubset(x))

# issuperset(): Returns True If all items in the specified set exists in the original
set, Else it retunes False.
x={1,2,3,4,5} O/P:
y={1,3,5} X issuperset Y: True
print("X issuperset Y:",x.issuperset(y)) Y issuperset X: False
print("Y issuperset X:",y.issuperset(x))

# len(): Returns number of elements present in Set


x={1,2,3,4,5} O/P:
print("set X:",x) set X: {1, 2, 3, 4, 5}
print("Length of Set:",len(x)) Length of Set: 5

 Frozenset:
 A frozen set is a collection of elements which is unordered and unindexed.
 Immutable
 We can create frozen set using frozenset() method.
 Syntax for creating a frozen set
s1 = {1,2,3,4,5}
fset = frozenset(s1)

39
LJIET Sem-5 PDS (3150713)

# frozenset() and Immutability


s={1,2,3,4}
print("set S:",s)
fs=frozenset(s)
print("FrozenSet=",fs)
fs.add(50) #Can’t add element as it is immutable
O/P:
set S: {1, 2, 3, 4}
FrozenSet= frozenset({1, 2, 3, 4})
AttributeError: 'frozenset' object has no attribute 'add'

#frozenset from list or tuple


l=[1,2,3,4]
fs1=frozenset(l)
print("FrozenSet From List=",fs1)
t=(5,6,7,8)
fs2=frozenset(t)
print("FrozenSet From Tuple=",fs2)
O/P:
FrozenSet From List= frozenset({1, 2, 3, 4})
FrozenSet From Tuple= frozenset({8, 5, 6, 7})

#Membership Operator
fs1=frozenset({1,2,3,4})
print(fs1)
print ("1 in fs1: ",1 in fs1)
print ("9 in fs1: ",9 in fs1)
O/P:
frozenset({1, 2, 3, 4})
1 in fs1: True
9 in fs1: False

#Accessing Items
fs1=frozenset({1,2,3,4})
for i in fs1:
print ('Item: ',i)
O/P:
Item: 1
Item: 2
Item: 3

40
LJIET Sem-5 PDS (3150713)

Item: 4
#concatenation of frozenset
fs1=frozenset({1,2,3,4})
fs2=frozenset({5,6,7})
print ("concatenation= ",fs1+fs2)

O/P: TypeError: unsupported operand type(s) for +: 'frozenset' and 'frozenset'

#Repetition of frozenset
fs1=frozenset({1,2,3,4})
print ("Repetition= ",fs1*2)

O/P: TypeError: unsupported operand type(s) for *: 'frozenset' and 'int'

#Slicing of frozenset
fs1=frozenset({1,2,3,4})
print ("Slicing= ",fs1[2])

O/P: TypeError: 'frozenset' object is not subscriptable

41
LJIET Sem-5 PDS (3150713)

 Practice Code:

# Odd-Even
n=int(input('Enter No:'))
if n%2==0:
print(n, ' is Even.')
else:
print(n, ' is Odd.')

# Factorial
n=int(input('Enter No:'))
f=1
while n>0:
f*=n
n-=1
print('Factorial is: ',f)

#Prime No
num=int(input('Enter No:'))
flag = False
if num > 1:
for i in range(2, num):
if (num % i) == 0:
flag = True
break
if flag:
print(num, "is not a Prime Number")
else:
print(num, "is a Prime Number")

#Seq of Prime No
num=int(input('Enter No:'))
for j in range(2,num+1):
flag = False
for i in range(2, j):
if (j % i) == 0:
flag = True
break
if flag:
print(j, "is not a Prime Number")
else:
print(j, "is a Prime Number")

42
LJIET Sem-5 PDS (3150713)

# Reverse of Given Number


N = int(input("Please Enter any Number: "))
Rev = 0
while(N > 0):
Reminder = N %10
Rev = (Rev *10) + Reminder
N = N //10
print("Reverse of entered number is = " ,Rev)

n=5 *
* *
for i in range(0,n): * * *
for j in range(0,i+1): * * * *
print("* ",end="") * * * * *
print("\r")

n=5 $ $ $ $ $
$ $ $ $
for i in range(5,0,-1): $ $ $
for j in range(0,i): $ $
print("$ ",end="") $
print("\r")

n=5 # # # # #
# # #
for i in range(5,1,-2): #
for j in range(0,i): # # #
print("# ",end="") # # # # #
print("\r")
for i in range(1,n+1,2):
for j in range(0,i):
print("# ",end="")
print("\r")

# Factorial wirh Recursion


def r_fact(n):
if n == 1:
return n
else:
return n*r_fact(n-1)

num = int(input("Please Enter any Number: "))


print("The factorial of", num, "is", r_fact(num))

43
LJIET Sem-5 PDS (3150713)

# Palindrom
s = input("String: ")
if (s==s[::-1]) :
print ('String is Palindrom')
else:
print ('String is not Palindrom')

Write a Python program which takes a list and returns a list with the elements "shifted l
eft by one position" so [1, 2, 3] yields [2, 3, 1].
n=input().split()
l=list(map(int,n))
print(l)
l.append(l.pop(0))
print('After Rotation: ',l)

Write a Python program which will return the sum of the numbers in the array, returnin
g 0 for an empty array. Except the number 13 is very unlucky, so it does not count and n
umber that come immediately after 13 also do not count.
n=input().split()
l=list(map(int,n))
print(l)
s=0
for i in range(len(l)):
if l[i]==13 or (l[i-1]==13 and i!=0):
continue
else:
s+=l[i]
print("Sum: ",s)

Write a program to interchange the List elements on two positions entered by a user.

l=[2,3,5,6,8,9,10]
print("List: ",l)
p1=int(input("Position 1:"))
p2=int(input("Position 2:"))
l[p1],l[p2]=l[p2],l[p1]
print('After Interchange: ',l)

44

You might also like