Unit I
Unit I
PYTHON PROGRAMMING
UNIT-1
Introduction: History of Python, Need of Python Programming, Applications Basics of
Python Programming Using the REPL(Shell), Running Python Scripts, Variables,
Assignment, Keywords, Input-Output, Indentation. Overview on Fundamental data
types of Python.
INTRODUCTION TO PYTHON:
➢ A program (computer program) is a set/sequence of instructions written in a
computer programming language instructing a computer to do specific tasks.
➢ “Software” is a generic term used to describe computer programs.
➢ A programming language is a computer language engineered to communicate
and provide instructions to a machine (computers).
➢ Types of Programming languages:
o High-level Language: [closure to the human languages]
▪ Close to Business problems-writing banking software, building an
e-commerce website, etc
▪ Ex: Python, C, C++, Perl, Java, Ada, JavaScript, Ruby, etc.
o Low-level Language: [closure to Hardware]
▪ Close to the system's problems-writing a device driver, memory
manager, anti-virus, etc
▪ Ex: Assembly level language, and Machine level language
Translation:
➢ Easier to program.
➢ Shorter and easier to read, and they are more likely to be correct.
Disadvantage:
➢ Programs have to be processed before they can run. This extra processing takes
some time
Interpreters Compilers
It takes a single line of code It takes an entire program at
Input
or instruction at a time. a time.
It does not produce any It generates intermediate
Output
intermediate object code. object code.
Compilation and execution The compilation is done
Working mechanism
take place simultaneously. before execution.
Speed Slower Comparatively faster
It requires less memory as it Memory requirement is more
Memory does not create intermediate due to the creation of object
object code. code.
Display all errors after
Displays error of each line
Errors compilation, all at the same
one by one.
time.
➢ General Purpose means Python is not specific to a particular area, happily we can
use Python for any type of application areas.
➢ For example:
o Database Access
➢ High-level programming languages are programmer-friendly languages, but not the
machine-friendly languages
➢ Need not worry about the low-level things i.e., memory management, security,
destroying the objects, and so on.
➢ In command-line mode, you type Python programs, and the interpreter prints the
result:
➢ >>> ->which is the prompt the interpreter uses to indicate that it is ready
(The >>> prompt is the Python interpreter’s way of asking you, “What do you want
me to do next?)
➢ Alternatively, you can write a program in a file and use the interpreter to execute the
contents of the file. Such a file is called a script.
Debugging:
➢ Programming is a complex process, and because it is done by human beings, it often
leads to errors.
➢ Programming errors are called bugs and the process of tracking them down and
correcting them is called debugging.
✓ Syntax errors: are like grammatical errors in English. Python has its own syntax.
Syntax refers to the structure of a program and the rules about that structure. They
occur when the defined rules are not followed.
For example,
▪ Mistyping a statement,
▪ Incorrect indentation,
These errors are usually easy to detect because Python tells you where they are and what
caused them.
prnt("Python is Easy")
Runtime errors
✓ The error does not appear until you run the program. These errors are also called
exceptions because they usually indicate that something exceptional (and bad) has
happened.
✓ Runtime errors are errors that cause a program to terminate abnormally. They occur
while a program is running if the Python interpreter detects an operation that is
impossible to carry out. Input mistakes typically cause runtime errors. An input error
occurs when the user enters a value that the program cannot handle. would cause a
runtime error
❑ If the program expects to read in a number, but instead the user enters a string
of text, this causes data-type errors to occur in the program.
✓ For example, suppose you wrote the program to convert a temperature (35
degrees) from Fahrenheit to Celsius.
print(5 / 9 * 35 - 32)
➢ Basically, All scripting languages are programming languages, but all programming
languages are not scripting languages.
CURRENT POPULARITY
HISTORY OF PYTHON
➢ When he began implementing python, Guido van Rossum was also reading the
published scripts from “Monty Python’s Flying circus” a BBC comedy series from the
1970s. Van Rossum thought he needed a name that was short, unique, and slightly
mysterious, so he decided the language python.
➢ Python was developed in 1989 while working at National Research Institute at the
Netherlands.
➢ But officially python was made available to the public is: Feb 20th, 1991.
➢ Developed python language by taking almost all programming features from different
languages
Scripting language means a group of lines of code will be executed line by line.
No functions concept, No classes concept, just a group of lines will be executed one by
one.
print("RGMCET, Nandyal")
print("Autonomous Engineering college")
print("Department of Mechanical Engineering")
print("Python Programming")
print("Python is a Scripting language")
Output:
RGMCET, Nandyal
Autonomous Engineering college
Department of Mechanical Engineering
Python Programming
Python is a Scripting language
def f():
print("RGMCET, Nandyal")
print("Autonomous Engineering College")
print("Department of Mechanical Engineering")
print("Python programming")
print("Python is a scripting language")
f()
Output:
RGMCET, Nandyal
Autonomous Engineering college
Department of Mechanical Engineering
Python Programming
Python is a scripting language
class python:
def designer():
print("Guido Van Rossum")
python.designer()
Output:
class python:
def designer():
p=python
p.designer()
Output:
In order to access the function inside the class all you have to do call the class with its
class name and with the “.” dot operator call its function. We can access the class in two
ways: Without creating the object and creating an object.
FEATURES OF PYTHON
print(i) System.out.println(i);
➢ The syntaxes are very simple and only 30+ (35 in python3.10.2) keywords are
available (in Java 53).
➢ When compared with other languages, we can write programs with a very less
number of lines. Hence more readability and simplicity.
➢ We can reduce the development and cost of the project
➢ freeware means we are not required to pay a single paisa for license-related issues
➢ Its source code is open so that we can customize based on our requirements.
➢ Open source means we can able to see source code how it is implemented, and we
can customize as per our requirement and you can introduce your python version.
Portability:
➢ Python programs are portable. i.e we can migrate from one platform to another
platform very easily. Python programs will provide the same results on any platform.
Dynamically Typed:
➢ In Python we are not required to declare the type for variables. Whenever we are
assigning the value, based on value, the type will be allocated automatically. Hence
Python is considered a dynamically typed language.
➢ But Java, C, C++, etc are Statically Typed Languages b'z we have to provide type at
the beginning only.
➢ This dynamic typing nature will provide more flexibility to the programmer.
Interpreted:
➢ We are not required to compile Python programs explicitly. Internally Python
interpreter will take care that compilation.
➢ If compilation fails interpreter raised syntax errors. Once compilation success then
PVM (Python Virtual Machine) is responsible to execute.
Extensible:
➢ We can use other language programs in Python [ Java code can be used in Python
using ‘Jython’, C# code can be accessed using Iron python].
• Let us assume that some C program is there, some Java program is there, can we
use these applications in our Python program or not?
1. Suppose We want to develop a Python application, assume that some xyz functionality
is required to develop the Python application.
2. There is some java code is already there for this xyz functionality. It is non-python
code. Is it possible to use this non-python code inside our python application?
Embedded:
• We can use Python programs in any other language programs. i.e we can embed
Python programs anywhere.
Extensive Library:
• Python has a rich inbuilt library.
• Being a programmer, we can use this library directly and we are not responsible to
implement the functionality. etc...
print(randint(0,9),randint(0,9),randint(0,9),randint(0,9),randint
(0,9),randint(0,9),sep = '')
Output:
228945 485642 168720 159855 282881 165049 962630 473469 371343 744817
Conclusions
➢ These are the 11 key features of Python programming language. Out of 11 Key
features, 3 Key features are specific to Python
▪ Dynamically Typed
▪ Extensive Library
➢ These 3 Features are not supported by any other programming languages like
C,C++ and Java etc.,
LIMITATIONS OF PYTHON:
➢ Suppose We want to develop mobile applications; Python is the worst choice. Why?
The main reason for this is Python, as of now, does not have library support to develop
mobile applications.
Android, IOs Swift are the kings in the Mobile application development domain.
To develop these end-to-end applications Python is not the best suitable, because, Python
doesn't have that much Library support to develop these applications as of now.
To improve performance, Now people have added the JIT compiler to the PVM. This works
in the following manner:
• Instead of interpreting line by line every time, a group of lines will be interpreted
only once and every time that interpreted code is going to use directly. JIT compiler
is responsible to do that.
• JIT compiler + PVM flavor is called pypy for better (Python for speed) version.
➢ Python’s shell provides an interface for the users to interact with the Python
interpreter.
➢ Python provides a Python Shell (also known as Python Interactive Shell) which is used
to execute a single Python command and get the result.
➢ Python Shell waits for the input command from the user. As soon as the user enters
the command, it executes it and displays the result.
➢ REPL is the language shell, the Python Interactive Shell. The REPL acronym is short
for Read, Eval, Print and Loop.
Loop: repeat.
A Python script is a file containing multiple lines of Python code saved with .py extension.
A Python script can be directly executed line by line without any need to compile it.
IDENTIFIERS
➢ An identifier must start with a letter or an underscore. It cannot start with a digit.
For example, import is a keyword, which tells the Python interpreter to import a module to
the program.
➢ One cannot use spaces and special symbols like !, @, #, $, % etc. as identifiers.
VARIABLE
➢ Variables are used to reference values that may be changed in the program.
➢ A variable is the way to store data while making it easy to refer to it later in our
code.
➢ A variable name must begin with either a letter or an underscore(_) followed by letters,
numbers, or underscore & unlimited in length.
➢ Variable names are case-sensitive. Ex: age and Age are not the same.
➢ Variable names conventionally have lower-case letters, with multiple words separated
by underscores. Ex: this_is_a_variable, simple_interest, date_of_birth, etc… are valid
variables. This is called the snake case.
➢ Variable names cannot be keywords & cannot start with numbers & cannot use
special symbols like !, @, #, $, % etc.
a = 3
b = 4
c = 5
avg = (a + b + c) / 3
print(avg)
4.0
Ex: Program: Calculate the simple interest when principal, interest rate and tenure are
given.
principal = 100000
tenure = 12
rate_of_interest = 0.05
It is always a good practice to choose descriptive names for variables. By looking at the
variable, one should be able to understand the purpose of it.
print() is an output function in python and is used to display output on the console or shell.
➢ The assignment statement creates new variables and gives them values.
➢ Where the equal sign (=) is used to assign value (right side) to a variable name (left
side).
Multiple Assignment
The basic assignment statement works for a single variable and a single expression.
Syntax:
var1=var2=var3...varn= = <expr>
Example:
x = y = z = 1
>>> x = y = z = 1
>>> print(x)
1
>>> print(y)
1
>>> print(z)
1
>>>
Syntax:
<var>, <var>, ..., <var> = <expr>, <expr>, ..., <expr>
Example:
x, y, z = 1, 2, "abcd"
In the above example x, y and z simultaneously get the new values 1, 2 and "abcd".
SWAP VARIABLES
Swapping two variables refers to mutually exchanging the values of the variables.
Generally, this is done with the data in memory.
Syntax:
var1, var2 = var2, var1
Example:
>>> x = 10
>>> y = 20
>>> print(x)
10
>>> print(y)
20
>>> x, y = y, x
>>> print(x)
20
>>> print(y)
10
KEYWORDS IN PYTHON
➢ Keywords are the reserved words, used to define the syntax and structure of the
Python language.
➢ These are reserved words with special meaning and purpose. They are used only for
the intended purpose.
➢ The interpreter uses the keywords to recognize the structure of the program
o Variable names,
o Function names or
o Any other identifiers.
>>> print(keyword.kwlist)
Key points:
INPUT-OUTPUT
We have two functions to handle input from a user and system in Python.
• input(prompt) to accept input from a user (to get the input from the user).
The input() function reads a line entered on a console by an input device such as a
keyboard and converts it into a string and returns it.
Input Using Mouse Click or movement, i.e. you clicked on the radio button or some
drop-down list and chosen an option from it.
Input ( )
Syntax: val = input(“prompt string”)
Example:
OUTPUT:
Example:
By default, the 'input()' function builds a string from the user’s keystrokes.
x = input()
print(type(x))
56
<class 'str'>
OUTPUT FUNCTION
x = "Apple"
y = 10
z = 21.5
print(x, y, z)
Apple 10 21.5
➢ Python print() function comes with a parameter called ‘end’.
print("Hello", end = ' ')
print("World!")
Hello World!
x = -100
y = 300
z = x + y
# normal way old style of printing
print(x, "plus", y, "is", z, "and", x, "is -ve")
# using format
print("{} plus {} is {} and {} is -ve".format(x, y, z, x))
print("{0} plus {1} is {2} and {0} is -ve".format(x, y, z))
# using f-string
print(f'{x} plus {y} is {z} and {x} is -ve')
INDENTATION
➢ Indentation is used to indicate blocks of code for class and function definitions or flow
control
➢ Indentation refers to the spaces (FOUR) or Tab space (ONE) at the beginning of a
code line.
➢ The first line of the function definition is called the header, the rest is called the body.
➢ The header has to end with a colon (:) and the body has to be indented.
➢ Where in other programming languages the indentation in code is for readability only,
the indentation in Python is very important. Interpreter returns Indentation Error when
we are not providing correct Indentation.
▪ Data types specify the different sizes and values that can be stored in the variable.
For example, Python stores numbers, strings, and a list of values using different
data types.
▪ In Python we are not required to specify the type explicitly. Based on the value
provided, the type will be assigned automatically and store value at some memory
location, and then binds that variable name to that memory. Hence Python is a
Dynamically Typed Language.
▪ Numeric types
• float - Real types are for representing numbers with a fractional part, Ex: 20.75
▪ Text type
• str – to represent collection of characters, Ex: 'Apple', " Apple ", '''Apple''' , """Apple"""
Note:
o All the numbers with decimal values will be treated as float it may be positive or
negative
o All the characters in between the quotes (single, double or triple quotes) will
be treated as strings.
▪ Sequence type
• List, tuple
▪ Dictionary - dict
▪ bytes
▪ bytearray
▪ memoryview
➢ None data type: None is not the same as 0, False, or an empty string. None is a
data type of its own (NoneType) and only None can be None.
For example, If we want to represent the roll number from 1 to 20, we can use
the range() type.
By default, it returns an iterator object that we can iterate using a for loop.
Note: In this, the type of 'x' has changed from 'int' to 'float', float to string, string to boolean
and later to 'complex' just by changing the value and running it.
Decimal form(base-10):
❑ It is the default number system in Python
❑ Eg: a =10
0.25 = (01) 2
4.25 = (100.01) 2
Binary form(base-2):
▪ The allowed digits are : 0 & 1
▪ Literal ( the data that are assigned to variables or constants) value should be
prefixed with 0b or 0B
Eg:
▪ a = 0B1111
▪ a =0B123
▪ a=0b111
Octal Form(base-8):
• The allowed digits are : 0 to 7
Hexadecimal Form(base-16):
• The allowed digits are : 0 to 9, a-f (both lower and upper cases are allowed)
By using these base conversion functions, we can convert from one base to another base.
Note: All these base conversion functions are applicable only for Integral numbers.
bin(): We can use bin() to convert from any other base to binary
>>> bin(15)
'0b1111'
>>> bin(0o123)
'0b1010011'
>>> bin(0xface)
'0b1111101011001110'
oct(): We can use oct() to convert from any other base to octal
>>> oct(0b1011011)
'0o133'
>>> oct(0xface)
'0o175316'
>>> oct(120)
'0o170'
hex(): We can use hex() to convert from any other base to hexa decimal
>>> hex(100)
'0x64'
>>> hex(0b1010)
'0xa'
>>> hex(0o12435)
'0x151d'
>>> f=2.345
>>> type(f)
<class 'float'>
Note: We can represent integral values in decimal, binary, octal and hexadecimal forms.
But we can represent float values only by using the decimal form.
• We can also represent floating point values by using exponential form (scientific
notation)
• The main advantage of exponential form is we can represent big values in less memory.
Eg:
3+5j
10+5.5j
0.5+0.1j
• In the real part if we use int value then we can specify that either by decimal, octal,
binary or hexadecimal form.
• But imaginary part should be specified only by using the decimal form.
>>> a=0B11+5j
>>> a
(3+5j)
>>> a=3+0B11j
SyntaxError: invalid syntax
>>> a=10+1.5j
>>> b=20+2.5j
>>> c=a+b
>>> print(c)
(30+4j)
>>> type(c)
<class 'complex'>
Note: Complex data type has some inbuilt attributes to retrieve the real part and imaginary
part
c = 10.5+3.6j
c.real ==>10.5
c.imag ==>3.6
b=True
type(b) =>bool
Eg:
a=10
b=20
c=a<b
print(c)==>True
True + True==>2
True - False==>1
Ex:
s1 = 'Apple'
s2 = "Apple"
s3 = '''Apple'''
s4 = """Apple"""
print(type(s1), type(s2), type(s3), type(s4))
<class 'str'> <class 'str'> <class 'str'> <class 'str'>
STRING CONCATENATION
Concatenation means to combine or add two things together. In this case, we want to
know how to add two strings together. This is very easy in Python.
x = "Hello "
y = "World"
print(x + y)
Hello World
In example, 'p' is stored only once and its reference (address) is placed twice, at index 1
and 2, in the list of characters.
s = "Apple"
print(id(s[0]), id(s[1]), id(s[2]))
Output:
23140185970928 23140186340272 23140186340272
Yes, strings are immutable. We cannot overwrite the values of immutable objects. The
storage for a string is fixed at construction and never alters. Obviously that makes handling
strings a lot simpler.
s = "Hello World!"
print(id(s))
s = "Welcome to PythonGuru"
print(id(s))
22711488237936
22711489300080
• If we observe the output, we can see that memory addresses do not match. That means
it’s not modifying the string object; it’s creating a new string object.
s = "Apple"
s[1] = 'd'
print(s)
----------------------------------------TypeError
Traceback (most recent call last)
<ipython-input-21-df9bb1f86711> in <module>()
1 s = "Apple"
----> 2 s[1] = 'd'
3 print(s)
TypeError: 'str' object does not support item assignment
We get a TypeError because strings are immutable. We can’t change the individual
characters of the string object.
An immutable object is an object that is not changeable and its state cannot be
modified after it is created.
o For example, the letter A is actually the number 65. This is called encoding. There are
two types of encoding for characters –ASCII and Unicode. ASCII uses 16 bits
for encoding whereas Unicode uses 32 bits. Python uses Unicode for character
representation.
o Index starts from 0 to n-1, where n is the number of characters in the string.
o Python allows negative indexing in strings. The index of -1 refers to the last item in
the string, -2 refers to the second last item , and so on.
Glyph Glyph
Binary Oct Dec Hex Binary Oct Dec Hex
1963 1965 1967 1963 1965 1967
010 0000 040 32 20 space 100 1001 111 73 49 I
010 0001 041 33 21 ! 100 1010 112 74 4A J
010 0010 042 34 22 " 100 1011 113 75 4B K
010 0011 043 35 23 # 100 1100 114 76 4C L
010 0100 044 36 24 $ 100 1101 115 77 4D M
010 0101 045 37 25 % 100 1110 116 78 4E N
010 0110 046 38 26 & 100 1111 117 79 4F O
010 0111 047 39 27 ' 101 0000 120 80 50 P
010 1000 050 40 28 ( 101 0001 121 81 51 Q
010 1001 051 41 29 ) 101 0010 122 82 52 R
010 1010 052 42 2A * 101 0011 123 83 53 S
010 1011 053 43 2B + 101 0100 124 84 54 T
010 1100 054 44 2C , 101 0101 125 85 55 U
010 1101 055 45 2D - 101 0110 126 86 56 V
010 1110 056 46 2E . 101 0111 127 87 57 W
010 1111 057 47 2F / 101 1000 130 88 58 X
011 0000 060 48 30 0 101 1001 131 89 59 Y
011 0001 061 49 31 1 101 1010 132 90 5A Z
011 0010 062 50 32 2 101 1011 133 91 5B [
011 0011 063 51 33 3 101 1100 134 92 5C \ ~ \
011 0100 064 52 34 4 101 1101 135 93 5D ]
011 0101 065 53 35 5 101 1110 136 94 5E ↑ ^
011 0110 066 54 36 6 101 1111 137 95 5F ← _
011 0111 067 55 37 7 110 0000 140 96 60 @ `
011 1000 070 56 38 8 110 0001 141 97 61 a
011 1001 071 57 39 9 110 0010 142 98 62 b
011 1010 072 58 3A : 110 0011 143 99 63 c
011 1011 073 59 3B ; 110 0100 144 100 64 d
011 1100 074 60 3C < 110 0101 145 101 65 e
011 1101 075 61 3D = 110 0110 146 102 66 f
011 1110 076 62 3E > 110 0111 147 103 67 g
011 1111 077 63 3F ? 110 1000 150 104 68 h
100 0000 100 64 40 @ ` @ 110 1001 151 105 69 i
100 0001 101 65 41 A 110 1010 152 106 6A j
100 0010 102 66 42 B 110 1011 153 107 6B k
100 0011 103 67 43 C 110 1100 154 108 6C l
100 0100 104 68 44 D 110 1101 155 109 6D m
100 0101 105 69 45 E 110 1110 156 110 6E n
100 0110 106 70 46 F 110 1111 157 111 6F o
100 0111 107 71 47 G 111 0000 160 112 70 p
100 1000 110 72 48 H 111 0001 161 113 71 q
Glyph Glyph
Binary Oct Dec Hex Binary Oct Dec Hex
1963 1965 1967 1963 1965 1967
111 0010 162 114 72 r 111 1001 171 121 79 y
111 0011 163 115 73 s 111 1010 172 122 7A z
111 0100 164 116 74 t 111 1011 173 123 7B {
111 0101 165 117 75 u 111 1100 174 124 7C ACK ¬ |
111 0110 166 118 76 v 111 1101 175 125 7D }
111 0111 167 119 77 w ~
111 1110 176 126 7E ESC |
111 1000 170 120 78 x
➢ The process of converting the value from one type to another type is known as
Type casting or Type Conversion.
➢ Python provides 5 in-built functions, which are used to convert the values from one
type to another type. These are listed as below:
▪ int()
▪ float()
▪ complex()
▪ bool()
▪ str()
int ( ): We can use int() function to convert other type values to int type.
print(int(5))
5
print(int(5.556))
5
print(int('10'))
10
print(int(True))
1
print(int(10.0+0.15j))
Traceback (most recent call last):
File "./prog.py", line 1, in <module>
TypeError: can't convert complex to int
print(int('10.5'))
Traceback (most recent call last):
File "./prog.py", line 1, in <module>
ValueError: invalid literal for int() with base 10: '10.5’
print(int('0b111'))
Traceback (most recent call last):
File "./prog.py", line 1, in <module>
ValueError: invalid literal for int() with base 10: '0b111'
Note:
➢ If we want to convert str type to int type, compulsory str should contain only integral
value and should be specified in base-10
float (): We can use float() function to convert other type values to float type .
print(float(5))
5.0
print(float(5.556))
5.556
print(float('10.5’))
10.5
print(float(True))
1.0
print(float(10.0+0.15j))
Traceback (most recent call last):
File "./prog.py", line 1, in <module>
TypeError: can't convert complex to float
print(float('0b111’))
Traceback (most recent call last):
File "./prog.py", line 1, in <module>
ValueError: could not convert string to float: '0b111’
print(float('ten’))
Traceback (most recent call last):
File "./prog.py", line 1, in <module>
ValueError: could not convert string to float: 'ten'
Note:
➢ If we want to convert str type to float type, compulsory str should contain only
integral or floating point value and should be specified in base-10
complex (): We can use complex() function to convert oth er types to complex
type.
Form 1 : complex(x)
We can use this function to convert x into complex number with real part x and imaginary
part 0.
print(complex(10))
(10+0j)
print(complex(0b111))
(7+0j)
print(complex(10.5))
(10.5+0j)
print(complex(True))
(1+0j)
print(complex(False))
0j
print(complex('10.5’))
(10.5+0j)
print(complex('ten'))
Traceback (most recent call last):
File "./prog.py", line 2, in <module>
ValueError: complex() arg is a malformed string
Form 2: complex(x,y) :We can use this method to convert x and y into complex number
such that x will be real part and y will be imaginary part.
print(complex(10,20))
(10+20j)
print(complex(0b111,0b1011))
(7+11j)
print(complex(10.5, 20.6))
(10.5+20.6j)
print(complex(True, True))
(1+1j)
print(complex(False, True))
1j
print(complex('10.5', '20.3'))
Traceback (most recent call last):
File "./prog.py", line 6, in <module>
TypeError: complex() can't take second arg if first is a string
print(complex(10.5, '20.3’))
Traceback (most recent call last):
File "./prog.py", line 2, in <module>
TypeError: complex() second arg can't be a string
Note:
bool( ): We can use this function to convert other type values to bool type.
print(bool(0.001)) print(bool(10.05+2j))
True True
print(bool(0.0)) print(bool(-10.25+1j))
False True
print(bool(0.001+0.1j))
If we pass complex type arguments
True
print(bool(1+1j))
print(bool(1+0j))
True
True
str() : We can use this method to convert other type values to str type
We can use this method to convert other type values to str type
print(str(10)) print(str(yes))
10 -------------------------------
print(str(10.58)) NameError
10.58 Traceback (most recent call last)
print(str(10.5+2j)) <ipython-input-11-16085fe22908>
(10.5+2j) in <module>()
print(str(True)) 5 print(str(False))
True 6 print(str(0b111))
print(str(False)) ----> 7 print(str(yes))
False NameError: name 'yes' is not
print(str(0b111)) defined
7
➢ All Fundamental Data types are immutable. i.e once we creates an object, we cannot
perform any changes in that object.
➢ If we are trying to change then with those changes a new object will be created. This
non-changeable behaviour is called immutability.
WHY IMMUTABILITY?
➢ Who is responsible for creating an Object in Python?
➢ In Python if a new object is required, then PVM won’t create an object immediately.
First, it will check if any object is available with the required content or not.
➢ If available then the existing object will be reused. If it is not available then only a new
object will be created.
x = "Mechanical"
y = "Mechanical"
z = "Mechanical"
print(id(x))
print(id(y))
print(id(z))
140503971214064
140503971214064
140503971214064
➢ But the problem in this approach is, several references pointing to the same object,
by using one reference if we are allowed to change the content in the existing object
then the remaining references will be effected. To prevent this immutability concept
is required.
➢ According to this, once creates an object we are not allowed to change content. If
we are trying to change with those changes a new object will be created.
➢ In the last example, we have proved that all the reference variables are pointing to
single object, we are used id() function to compare their addresses.
➢ Instead of comparing the addresses, we can use a short-cut approach also. i.e.,
we can make use of is operator.
x = "Mechanical"
y = "mechanical"
print(x is y)
False
140503971214064
140503970840624
Immutability vs Mutability
Python generally pools integers between -5 to +256, in the pre-allocated object list. This
is also applicable for characters(str) after all ASCII codes are integers.
Note
o list
o tuple
o set
o frozenset
o dictionary
LIST:
➢ List is a collection of items (Python objects) that are ordered and mutable.
➢ The purpose of the list is, to group up the things, which fall under the same category.
➢ Examples
➢ As a group of similar elements stored in a list, mostly those are homogeneous (of the
same data type). Creating a list in python is putting different comma-separated-
values, between square brackets ([ ]).
➢ Even though the list principle suggests homogeneous data items in it, it is not
mandatory and still allowed to have different types which make it the most powerful
tool in Python
✓ Growable in nature, i.e based on our requirement we can increase or decrease the
size.
✓ Applications: If the content is keep on changing, better to opt for list type. For
example, Youtube comments or Facebook comments or Udemy reviews (which are
keep on changing day by day).
TUPLE:
➢ A tuple is a data type similar to a list.
➢ The major differences between the two are: Lists are enclosed in square
brackets [] and their elements and size can be changed (mutable), while tuples are
enclosed in parentheses () and their elements cannot be changed (immutable).
Note: Since a tuple is immutable, iterating through a tuple is faster than with a list. This
gives a slight performance improvement.
➢ Once a tuple is defined, we cannot add elements in it or remove elements from it.
A tuple can be converted into a list so that elements can be modified and converted
back to a tuple.
For example, In Banks, account type - Only 2 values are there, 1. Savings 2. Current
At runtime account types never going to change throughout Bank Project. So, to represent
bank account types, better to go for the tuple concept.
Some other Examples, Where allowed inputs are fixed (Best suitable type is tuple):
1. Vendor machines (Only accept 2/-,5/- coins only)
2. In the Metro stations also, If you want to get the tickets, you have to insert either 10/-
note or 20/- note only
List Tuple
Mutable Immutable
Dynamically resizable array Fixed in size
To store list elements python virtual To store tuple elements python virtual memory
memory requires more memory requires less memory.
Emphasizes on quantity Emphasizes on structure
Unhashable Hashable
Use square brackets Use parenthesis (Optional sometimes)
Comma not required when having a single
Comma is required when having a single element
element
Tuple elements can access within less time,
Performance is less compared to tuple.
because they are fixed (performance is more)
SET:
➢ A set is a mutable data type and We can add or remove items / elements from it.
➢ The set data type is, as the name implies, a mathematical set.
➢ Set does not allow duplicates. Set does not maintain order. This is because the
placement of each value in the set is decided by an arbitrary index produced by the
hash() function. So, we should not rely on the order of set elements, even though
sometimes it looks like order.
➢ Internally uses a hash table. Values are translated to indices of the hash table using
the hash() function. When a collision occurs in the hash table, it ignores the element.
This explains, why sets unlike lists and tuples can't have multiple occurrences of the
same element. type() of set is 'set'.
Note : Mutable data types like list, set and dictionary cannot become elements of a set.
➢ Membership testing
➢ For example, we want to send one SMS to all the students of a class. In this
duplicate numbers are not allowed and in any order, we can send SMS. At
last, all the students should receive the message. if you have such type of
requirement, then it is better to go for the set data type.
➢ Duplicate elements are allowed in the list, but duplicate elements are not allowed in
the set.
➢ List can be represented by using square brackets and set can be represented by using
curly braces.
FROZENSET(): IS IMMUTABLE
➢ The frozenset() is an inbuilt function in Python which takes an iterable object as input
and makes them immutable. Simply it freezes the iterable objects and makes them
unchangeable.
➢ In Python, frozenset is same as set except its elements are immutable. This function
takes input as any iterable object and converts them into immutable object. The order
of element is not guaranteed to be preserved.
➢ In general, meaning of frozen is freezing, i.e, No one going to change, can't move,
fixed etc.,
➢ Frozen set is exactly same as set except that it is immutable. Hence we cannot use
add or remove functions
What is the difference between Frozen set and tuple data types?
1. In tuple, order is preserved, but in frozen set order is not applicable.
2. In tuple duplicate elements are allowed, but in frozen set duplicates are not allowed.
3. Index, slice concepts are applicable, but in frozen set index,slice concepts are not
applicable.
Note : The only similarity between tuple and frozen set is, both are immutable.
DICTIONARY
➢ If you observe this, all these data types are talks about a group of individual values.
Some times, If we want to represent a group of values as key-value pairs then we
should go for dict data type.
➢ Let's take a list l = [34, 32.5, 33, 35, 32, 35.1, 33.6]
➢ Suppose the above list l is representing the maximum temperatures of the last week,
from Sunday to Saturday. How do you access max temperature on Thursday?
➢ Dictionary is an associative container, which has a set of Key-Value pairs. 'Key' is the
'Index', through which we access associated value.
Dictionary is an unordered data structure and it is a collection of key and value pairs.
In a dictionary, the keys should be unique, but the values can change. For example,
the price of a commodity may change over time, but its name will not change.
Immutable data types like number, string, tuple etc. are used for the key and any data
Binary Types
Binary data types are the types made-up of bytes.
▪ bytes
▪ bytearray
▪ Memoryview
b = b"Apple" # bytes
print("b: ", type(b))
ba = bytearray(5) # bytearray
print("ba: ", type(ba))
mv = memoryview(b"2") # memory view
print("mv: ", type(mv))
b: <class 'bytes'>
ba: <class 'bytearray'>
mv: <class 'memoryview'>
bytes Data Type: it is not much frequently used data type in python
▪ bytes data type represents a group of byte numbers just like an array.
▪ Eg:
x = [10,20,30,40]
b = bytes(x)
type(b)==>bytes
print(b[0])==> 10
print(b[-1])==> 40
>>> for i in b : print(i)
10
20
30
40
▪ Conclusion 1:
The only allowed values for byte data type are 0 to 256. By mistake if we are trying
to provide any other values then we will get value error.
Conclusion 2:
Once we creates bytes data type value, we cannot change its values, otherwise, we
will get TypeError.
Eg:
>>> x=[10,20,30,40]
>>> b=bytes(x)>>> b[0]=100
20
30
40
b[0]=100
for i in b: print(i)
100
20
30
40
Eg 2:
>>> x =[10,256]
>>> b = bytearray(x)
ValueError: byte must be in range(0, 256)
Memory view
memoryview objects allow Python code to access the internal data of an object that
supports the buffer protocol without copying. The memoryview() function allows direct
read and write access to an object’s byte-oriented data without needing to copy it first.
Syntax: memoryview(obj)
byte_array = bytearray('XYZ', 'utf-8')
mv = memoryview(byte_array)
print(mv[0])
print(bytes(mv[0:1]))
Output:
88
b'X
OPERATORS:
What is an Operator?
Operators are symbols, such as +, –, =, >, and <, that perform (action on operands) certain
mathematical or logical operation to manipulate data values and produce a result based
on some rules.
x+y
• Types:
➢ Arithmetic Operators
➢ Assignment operators
➢ Logical operators
➢ Bitwise operators
➢ Shift operators
➢ Ternary operator
➢ Membership operators
➢ Identity operators
Arithmetic operators
Arithmetic operators are used to perform common mathematical operations or arithmetic
operations.
Note: For any number x, x/0 and x%0 always raises "ZeroDivisionError"
10/0
10.0/0
// - Integer Division
print(7 / 2) # Division
print(7 // 2) # Integer or Floor Division
print(7 // 2.0) # Integer or Floor Division
print(7.0 // 2) # Integer or Floor Division
print(7.0 // 2.0) # Integer or Floor Division
3.5
3
3.0
3.0
3.0
print(math.ceil(10.3))
Output:11
Example-1
Write a program to read two int inputs from the user and display the results of the
arithmetic operations:
Ex: 5 Write a program to find quotient and remainder of the given two
values using divmod()
Output:
For example, if the user gives the input as:
Enter number-1: 12
Enter number-2: 4
Sample Input and Output:
Enter number-1: 45
Enter number-2: 3
45 // 3 = 15
45 % 3 = 0
The operands can be Numbers or Strings or Boolean values. Strings are compared letter
by letter using their ASCII values, thus, “P” is less than “Q”, and “Aston” is greater than
“Asher”.
Equal to (==) & Not Equal to ( !=) are called Equality operators and the remaining are
relational operators.
Equality Operators:
Equality operators are used to check whether the given two values are equal or not. The
following are the equality operators used in Python.
1. Equal to (==)
2. Not Equal to (!=)
print(10==20)
print(10!=20)
False
True
print(1==True)
print(10==10.0)
print(‘Mechanical'==‘Mechanical')
True
True
True
We can apply these operators for any type even for incompatible types also.
print(10==‘Mechanical')
False
print(10=='10')
False
Note:
The Chaining concept is applicable for equality operators.
If at least one comparison returns False then the result is False. Otherwise, the result is
True.
print(10==20==30==40)
print(10==10==10==10)
False
True
Comparison operators-strings
• All the comparison operators work on strings also. The result is either True or False.
• Python compares strings using the Unicode value of the characters (lexicographical).
• The comparison is made by taking the ordinal values of each character in the string
and comparing it with the ordinal values of the character at the same position in the
other string.
• If the ordinal value of the character in the first string is greater than the ordinal value
of the character in the second string, then the comparison stops and the first string is
declared greater than the second string. The length of the string does not matter.
• In Python, the ordinal value of a character can be found using the ord() function, which
takes the character as an argument.
print(ord('P'))➔80
print(ord('Q')) ➔81
print(chr(97)) ➔a
print(chr(65)) ➔A
During execution, the program should print the message on the console as:
• In the chaining, if all comparisons return True then the only result is True.
print(10<20) # ==>True
print(10<20<30) # ==>True
print(10<20<30<40) # ==>True
print(10<20<30<40>50) # =>False
Assignment operators
Assignment Operators are used to assigning values to variables.
Operator Description Expression and its result
Ex:
Logical operators
Logical operators are used to combining multiple relational expressions into one.
A logical operator is derived from Boolean algebra where the result is either True or False.
It is generally used to represent logical comparison the way it is done in real life.
1 represents True and 0 represents False. (Internally 0 represents False and anything
else represents True)
The logical operators supported in Python are similar to the logic gates and are as follows:
1. and - Logical AND: The result is True, only if both the operands are True. ( 1 and
1 is the only condition where the result is 1, any other combination results in 0.)
2. or - Logical OR: The result is True if any one of the operands is True. ( 0 and 0 is
the only condition where the result is 0, any other combination results in 1.)
3. not - Logical NOT: The result negates the operand, i.e if the operand is True, the
result is False and vice versa
0 means False
Ex:
Ex:
Take two inputs from the user using input() function, one is gender of the person
either M or F in string format and another one is age of the person in integer format. Write
a simple program to see whether the given person is eligible for concession or not and
print the result as shown in the examples:
Follow these instructions to identify whether the person is eligible for the concession or
not.
If the person is female and age >= 60, Eligible for concession.
Enter a: 59
Enter b: 6
True
Enter a: 30
Enter b: 30
False
Write a program to understand the logical not operator. The program should
print Weekend if the day is either SAT or SUN, otherwise it should print Not Weekend.
Take the input day from the user.
Weekend
Not Weekend
If x is x and y is
“truthy” y
“falsy” x
Here, X and Y are non-boolean types and the result may be either X or Y but not
boolean type (i.e., The result is always non-boolean type only).
if 'X' is evaluated to false then the result is 'X'.
If 'X' is evaluated to true then the result is 'Y'.
engineering
mechanical
not X:
Even you apply not operator for non boolean type, the result is always boolean type only.
If X is evaluates to False then result is True otherwise False
Bitwise operators
• Bitwise operators are used to perform bitwise calculations on integers.
• Bitwise operators are used to manipulating values at the bit and byte level.
• The integers are first converted into binary and then operations are performed on bit
by bit, hence the name bitwise operators.
• Then the result is returned in a decimal format which will be printed on the console or
shell.
• These operators are applicable only for int and boolean types. By mistake, if we are
trying to apply for any other type then we will get an Error.
0 & 0 -> 0
0 & 1 -> 0
1 & 0 -> 0
Operator copies a bit to the
1 & 1 -> 1
& Bitwise AND result if it exists in both
Ex: x=0b1010
operands
y=0b1100
Print(bin(x&y)
‘0b1000’
^ Bitwise XOR It copies the bit if it is set in 0^0 -> 0 Ex: x=0b1010
one operand but not both. 0^1 -> 1 Y=0b1100
1^0 -> 1 print(bin(x^y)
1^1 -> 0 ‘0b110’
Bitwise AND Bitwise OR Bitwise XOR and Assign Bitwise Left Bitwise Right Shift
and Assign and Assign Shift and and Assign:
Assign
In Python, negative numbers are represented in 2's complement integer format. A 2's
compliment is (1's compliment + 1).
Shift operators
Bit-wise Left Shift
x = 20
print (x << 3)
print(x)
160
20
In this example we are shifting bits of 20 (i.e 0b10100) 3 times to the left side, which
becomes 0b10100000 i.e.., Three 0s are added to the right side.
Note:
When x is shifted n times to the left side, its value becomes x * 2^n.
In this example we are shifting bits of 160 (i.e 0b10100000) 3 times to the right side, which
becomes 0b10100. Three bits are discarded from right side.
Note:
When x is shifted n times to the right side, its value becomes x / 2^n.
The ternary operator can be thought of as a simplified, one-line version of the if-else
statement to test a condition.
Syntax
Eg 1:
a, b=23,43 # a =23 b = 43
c = 50 if a>b else 100
print(c)
100
Eg 2: Read two integer numbers from the keyboard and print minimum value using
ternary operator
a=int(input("Enter First Number:"))
b=int(input("Enter Second Number:"))
min=a if a<b else b
print("Minimum Value:",min)
Enter First Number:255
Enter Second Number:22
Minimum Value: 22
Membership Operator
The Right Hand Side (RHS) can be a String, List, Tuple, Set or a Dictionary.
For strings, the Left Hand Side (LHS) can be any string. If this string exists in the RHS
string, then True is returned. Otherwise False is returned.
For all other data types (Lists, Tuples, Sets, Dictionaries, etc.) the LHS should be a
single element.
Operator Description
in Returns true if value / variable found in the specified sequence and false otherwise.
not in Returns true if value / variable not found in the specified sequence and false
otherwise.
Ex:
Ex:2
list1=["sunny","bunny","chinny","pinny"]
print("sunny" in list1)
print("tunny" in list1)
print("tunny" not in list1)
True
False
True
The ‘is‘ operator compares the identity of two objects, the id() function returns an integer
representing its identity (currently implemented as its address).
If two integer or string variables have the same value, they point to the same memory
location.
But this is not true with floating-point numbers, lists, tuples, and dictionaries.
We can use identity operators for address comparison. There are two identity operators
used in Python:
i) is
ii) is not
r1 is r2 returns True if both r1 and r2 are pointing to the same object.
r1 is not r2 returns True if both r1 and r2 are not pointing to the same object
a=10
b=10
print(a is b)
True
x=True
y=True
print( x is y)
True
Ans: Whenever 'a' and 'b' pointing to the same object, then only 'a is b' returns true,
which is nothing but reference comparison (or) Address comparison.
Ex:
a=10
b=10
print(a is b)
print(id(a))
print(id(b))
True
2179289973264
2179289973264
• == Operator : ==' is meant for content comparison
Ex:
l1 = [10,20,30]
l2 = [10,20,30]
print(id(l1))
print(id(l2))
print(l1 is l2) # False
print(l1 == l2) # True
l3 = l1 # l3 is also pointing to l1
print(id(l3))
print(l1 is l3) # True
print(l1 == l3) # True
Operator precedence determines the way in which operators are parsed with respect to
each other.
Operators with higher precedence become the operands of operators with lower
precedence. Associativity determines the way in which operators of the same precedence
are parsed. Almost all the operators have left-to-right associativity. Operator precedence
is listed in TABLE. starting with the highest precedence to lowest precedence.
UNIT-II
Syllabus:
Input and Output statements: input() function, reading multiple values from the keyboard
in a single line, print() function, ‘sep’ and ‘end’ attributes, Printing formatted string,
replacement operator ({}). Control flow statements: Conditional statements. Iterative
statements. Transfer statements.
Input ( ):
➢ input() function can be used to read data directly in our required format.
➢ In Python3, we have only the input() method and the raw_input() method (Python2)
is not available.
➢ Why does input() in Python 3 give priority to string type as return type?
Reason: The most commonly used type in any programming language is str type,
that's why they gave priority to str type as the default return type of input() function.
Ex1:
num1 = input("Enter num1: ")
num2 = input("Enter num2: ")
print('The sum of two numbers =', num1+num2)
output:
Enter num1: 15
Enter num2: 50
The sum of two numbers = 1550
Ex2:
num1 = int(input("Enter num1: "))
num2 = int(input("Enter num2: "))
print('The sum of Two numbers = ', num1+num2)
output:
Enter num1: 5
Enter num2: 6
The sum of Two numbers = 11
Ex3:
num1 = float(input("Enter num1: "))
num2 = float(input("Enter num2: "))
print('The sum of two numbers =', num1+num2)
output:
Enter num1: 5.2
Enter num2: 3
The sum of two numbers = 8.2
Program: Write a program to read Employee data from the keyboard and print that data.
Employee_Number = int(input("Enter Employee No:"))
Employee_Name = input("Enter Employee Name:")
Employee_salary = float(input("Enter Employee Salary:"))
Employee_address = input("Enter Employee Address:")
Employee_marital_status = bool(input("Employee Married or Not
Married:"))
print("Please Confirm your provided Information")
print("Employee No :",Employee_Number)
print("Employee Name :",Employee_Name)
print("Employee Salary :",Employee_salary)
print("Employee Address :",Employee_address)
print("Employee Married ? :", Employee_marital_status)
➢ This function generally breaks the given input by the specified separator and in case
the separator is not provided then any white space is considered as a separator.
➢ This function is generally used to separate a given string into several substrings.
However, you can also use it for taking multiple inputs.
➢ separator: This is a delimiter. The string splits at this specified separator. If it is not
provided then any white space is a separator.
➢ maxsplit: It is a number, which tells us to split the string into a maximum of provided
number of times. If it is not provided then the default is -1 which means there is no
limit.
Taking multiple inputs at a time and type casting using the list() function.
b) input ()
You can take multiple inputs in one single line by using the input function several times as
shown below.
map() is another function that will help us take multiple inputs from the user. In general,
the syntax for the map function is the map (fun, iter). Here fun is the function to which the
map function passes each iterable.
List data types also help in taking multiple inputs from the user at a time. The syntax for
creating a list and storing the input in it is
List allows you to take multiple inputs of different data type at a time. The below example
will help you understand better.
Here, we are using only one input function (i.e., input("Enter Your name and age:")). So
whatever you provide is treated as only one string.
Suppose, you are providing input as Face Prep, 20, this is treated as a single string.
If you want to split that string into multiple values, then we are required to use the split()
function.
If we want to split the given string (i.e., Face Prep 20) with respect to space, then the code
will be as follows:
Now this single string(i.e., Face Prep, 20) is splitted into a list of two string values.
x,y = [x for x in input(("Enter Your name and age: ").split()] ===> it assigns Face Prep to x
and 20 to y. This concept is called list unpacking.
2 Inputs at a Time:
eval():
eval() Function is a single function that is the replacement of all the typecasting functions
in Python.
If you provide an expression as a string type, eval Function take a String and evaluate the
Result.
Eg:
x = eval('10+20+30')
print(x)
Output: 60
Eg:
x = eval(input('Enter Expression'))
Enter Expression: 10+2*3/4
Output: 11.5
Output function: print()
We can use print() function to display output to the console for end user sake.
print("Mechanical Engineering")
print("RGMCET: ")
Output:
Mechanical Engineering
RGMCET
Ex2:
print("Mechanical Engineering")
print()
print("RGMCET")
Output:
Mechanical Engineering
RGMCET
a, b, c = 10,20, 30
print("The values are: ", a, b, c)
The values are: 10 20 30
Ex2:
print("The values are: ", a, b, c, sep = ',')
The values are: ,10,20,30
If we want to output in the same line with space, we need to use the end attribute.
➢ We can use commas to print multiple variables / values at a time as shown below.
x = "Apple"
y = 10
z = 21.5
print(x, y, z)
Apple 10 21.5
Ex:
list=[1,2,3,4,5]
tuple=(1,2,3,4,5)
set={"mech", 'engg'}
dict={"Mech":1995, "dept":2022}
print(list)
print(tuple)
print(set)
print(dict)
Form-7: print(String, variable list):
We can use print() statement with String and any number of arguments.
Ex:
a = 'Mechanical'
b = 'students'
c = 'python programming class'
print("Hello", a, "Engineering", b)
print("welcome", 'to',c)
Hello Mechanical Engineering students
welcome to python programming class
• %i====>int
• %d====>int
• %f=====>float
• %s======>String type
Ex:
a=10
b=20.5
c=30.3
s= "Hello Dear"
l=[10, 20, 50, 60]
print("a value is %i" %a)
print("b value is %f and c value is %f" %(b,c))
print("Hi %s....your items:%s" %(s,l))
output:
a value is 10
b value is 20.500000 and c value is 30.300000
Hi Hello Dear....your items:[10, 20, 50, 60]
# using f-string
print(f'{x} plus {y} is {z} and {x} is -ve')
Ex:
a,b,c,d = 10,20,30,40 # print a=10,b=20,c=30,d=40
print('a = {},b = {},c = {},d = {}'.format(a,b,c,d))
▪ We may need to direct the program's flow to another part of your program
without evaluating conditions.
➢ In such cases, control structures become handy. Control structures are mainly used
to control the flow of execution. They are used for decision making which means we
execute code only if certain criteria is matching.
➢ You can execute different blocks of codes depending on the outcome of a condition.
➢ if statement
➢ if-else
➢ if-elif-else
➢ nested if-else
if Statement (One-way):
' if ' statement is used to decide whether a certain statement(s) have to be executed or
not.
Syntax:
if condition:
statements
▪ The : symbol is also used to start an indent suite of statements in case of if,
while, for, def and class statements
The : operator slices a part from a sequence object such as list, tuple or string. Ex: >>>
a=[1,2,3,4,5]
>>> a[1:3]
[2, 3]
INDENTATION:
▪ All the statements which need to be executed when the condition is True, should be
placed after 'if condition:' preceded by one tab(generally 4 spaces).
▪ All the statements after 'if' statement with one tab indentation, are considered as if
block
Ex:
In the above example, if the number is positive or zero then only 'if' block will get executed
Ex:
Program on if statement
if-else
When we want to execute two blocks of code exclusively, we use the 'if-else' statement.
Only one block of code will be executed all the time.
Syntax:
if condition:
statements
else:
statements
Ex:
Program 1:
Another way:
def isPalindrome(s):
return s == s[::-1]
# Driver code
s = "malayalam"
ans = isPalindrome(s)
if ans:
print("Yes")
else:
print("No")
output:
Yes
if-elif-else Statement:
When we have multiple exclusive cases, we use 'if-elif ladder'. Only one block of code will
be executed at any time.
Syntax:
if condition:
statements
elif condition:
statements
elif condition:
statements
.
.
.
else:
statements
Ex: Program to print the greatest number among three numbers.
Ex:
# Python program to check if year is a leap year or not
year = 2000
# if not divided by both 400 (century year) and 4 (not century year)
# year is not leap year
else:
print("{0} is not a leap year".format(year))
Output:
2000 is a leap year
Ex:
Program to print the grade assigned to the obtained marks.
➢ Python provides us the following two loop statements to perform some actions
repeatedly
▪ for loop
▪ while loop
• In the syntax, i is the iterating variable, and the range specifies how many times
the loop should run. For example, if a list contains 10 numbers then for loop will
execute 10 times to print each number.
• In each iteration of the loop, the variable i get the current value.
• Definite Iteration: When we know how many times we wanted to run a loop, then we
use count-controlled loops such as for loops. It is also known as definite iteration.
• Reduces the code’s complexity: Loop repeats a specific block of code a fixed
number of times. It reduces the repetition of lines of code, thus reducing the
complexity of the code. Using for loops and while loops we can automate and repeat
tasks in an efficient manner.
• Loop through sequences: used for iterating over lists, strings, tuples, dictionaries,
etc., and perform various operations on it, based on the conditions specified by the
user.
Ex:
To display numbers from 0 to 5
for num in range(0,6):
print(num)
output:
0
1
2
3
4
5
Ex:
numbers = [1, 10, 20, 30, 40, 50]
sum = 0
# Find sum of all the numbers using for loop
for i in numbers:
sum = sum + i
print ("The sum of numbers is", sum) # print sum here
colors = ['red', 'orange', 'green', 'yellow', 'white', 'violet']
for i in colors:
print(i)
# Similarly ierate over the given colors and print the colors
Ex:
To display odd numbers from 0 to 10
for num in range(0,10):
if num%2 !=0:
print(num)
1
3
5
7
9
Ex:
To display even numbers from 0 to 10
for num in range(0,10):
if num%2 ==0:
print(num)
0
2
4
6
8
Ex:
To display numbers from 5 to 1 in descending order.
for num in range(5,0,-1):
print(num)
5
4
3
2
1
Ex: Write a Program to print characters present in the given string
str = "MECHANICAL"
for x in str:
print(x)
M
E
C
H
A
N
I
C
A
L
Example: Calculate the average of list of numbers
numbers = [10, 20, 30, 40, 50] #numbers = eval(input("Enter list"))
# definite iteration
# run loop 5 times because list contains 5 items
sum = 0
for i in numbers:
sum = sum + i
list_size = len(numbers)
average = sum / list_size
print("Sum of List of numbers: ", sum)
output:
Sum of List of numbers: 150
Average of List of numbers: 30.0
Ex:
# Python program to find the factorial of a number provided by the user.
factorial = 1
else:
for i in range(1,num + 1):
factorial = factorial*i
print("The factorial of",num,"is",factorial)
Output:
The factorial of 7 is 5040
▪ There is a typical structure to print any pattern, i.e., the number of rows and
columns. We need to use two loops to print any pattern, i.e., use nested loops.
▪ The outer loop tells us the number of rows, and the inner loop tells us the column
needed to print the pattern.
▪ Accept the number of rows from a user using the input() function to decide the size
of a pattern.
➢ Iterate rows
▪ Next, write an outer loop to Iterate the number of rows using a for loop and range()
function.
➢ Iterate columns
▪ Next, write the inner loop or nested loop to handle the number of columns. The
internal loop iteration depends on the values of the outer loop.
▪ Use the print() function in each iteration of the nested for loop to display the symbol
or number of a pattern (like a star (asterisk *) or number).
▪ Add a new line using the print() function after each iteration of the outer loop so that
the pattern display appropriately
Program:
rows = int(input('Enter no.of rows : '))
for i in range(rows):
for j in range(i+1):
print('*', end = ' ')
print()
Ex2:
* * * * * *
* * * * *
* * * *
* * *
* *
*
Program:
rows = int(input('Enter no.of rows : '))
for i in range(rows):
#for j in range(rows-i):
for j in range(i, rows):
print('*', end = ' ')
print()
Ex3:
*
* *
* * *
* * * *
* * * * *
* * * * * *
Program:
rows = int(input('Enter no.of rows : '))
for i in range(rows):
for j in range(i,rows):
print(' ', end = ' ')
for j in range(i+1):
print('*', end = ' ')
print()
Ex:
* * * * * *
* * * * *
* * * *
* * *
* *
*
Program:
rows = int(input('Enter no.of rows : '))
for i in range(rows):
for j in range(i+1):
print(' ', end = ' ')
for j in range(i,rows):
print('*', end = ' ')
print()
for j in range(i+1):
print('*', end = ' ')
for j in range(i):
print('*', end = ' ')
print()
for i in range(rows):
for j in range(i+1):
print(' ', end = ' ')
for j in range(i,rows):
print('*', end = ' ')
for j in range(i,rows-1):
print('*', end = ' ')
print()
Ex:
num = 29
# program
str1 = "Race"
str2 = "Care"
# convert both the strings into lowercase
str1 = str1.lower()
str2 = str2.lower()
# check if length is same
if(len(str1) == len(str2)):
# sort the strings
sorted_str1 = sorted(str1)
sorted_str2 = sorted(str2)
# if sorted char arrays are same
if(sorted_str1 == sorted_str2):
print(str1 + " and " + str2 + " are anagram.")
else:
print(str1 + " and " + str2 + " are not anagram.")
else:
print(str1 + " and " + str2 + " are not anagram.")
output:
race and care are anagram.
While loop:
'while' loop is used to execute a block of statements repeatedly as long as a condition is
true. Once the condition is false, the loop stops execution and control goes immediate
next statement after while block.
▪ The while statement checks the condition. The condition must return a boolean
value. Either True or False.
▪ Next, If the condition evaluates to true, the while statement executes the statements
present inside its block.
▪ The while statement continues checking the condition in each iteration and keeps
executing its block until the condition becomes false.
• Automate and repeat tasks.: As we know, while loops execute blocks of code over
and over again until the condition is met it allows us to automate and repeat tasks in
an efficient manner.
• Indefinite Iteration: The while loop will run as often as necessary to complete a
particular task. When the user doesn’t know the number of iterations before
execution, while loop is used instead of a for loop
• Reduce complexity: while loop is easy to write. using the loop, we don’t need to
write the statements again and again. Instead, we can write statements we wanted
to execute again and again inside the body of the loop thus, reducing the complexity
of the code
• Infinite loop: If the code inside the while loop doesn’t modify the variables being
tested in the loop condition, the loop will run forever.
Ex:
To print numbers from 1 to 5 by using while loop
x=1
while x <=5:
print(x)
x=x+1
To display the sum of first n numbers
n=int(input("Enter number:"))
sum=0
i=1
while i<=n:
sum=sum+i
i=i+1
print("The sum of first",n,"numbers is :",sum)
Ex: # Python program to find the sum of integers between 0 and n where
n is provided by user
num = int(input("Enter a number: "))
s = 0
if (num >= 0):
while (num >= 0):
s = s + num
num = num - 1
print('The sum is {}'.format(s))
elif (num < 0):
while (num < 0):
s = s + num
num = num + 1
print('The sum is {}'.format(s))
Sample Input and Output 1:
Enter a number: 250
The sum is 31375
Ex:
Python Program to Print the Fibonacci sequence
# Program to display the Fibonacci sequence up to n-th term
n1, n2 = 0, 1
count = 0
Statement Description
Terminate the current loop. Use the break statement to come out of the loop
break
instantly.
continue Skip the current iteration of a loop and move to the next iteration
Do nothing. Ignore the condition in which it occurred and proceed to run the
pass
program as usual
• For example, you are searching a specific email inside a file. You started reading a
file line by line using a loop. When you found an email, you can stop the loop using
the break statement.
In the first iteration of the loop, 10 gets printed, and the condition i > 100 is checked.
Since the value of variable i is 10, the condition becomes false.
In the second iteration of the loop, 40 gets printed again, and the condition i > 100 is
checked. Since the value of i is 40, the condition becomes false.
In the third iteration of the loop, the condition i > 100 becomes true, and the break
statement terminates the loop
Continue Statement
The continue statement skip the current iteration and move to the next iteration. In Python,
when the continue statement is encountered inside the loop, it skips all the statements
below it and immediately jumps to the next iteration.
In some situations, it is helpful to skip executing some statement inside a loop’s body if a
particular condition occurs and directly move to the next iteration.
We used the continue statement along with the if statement. Whenever a specific
condition occurs and the continue statement is encountered inside a loop, the loop
immediately skips the remaining body and moves to the next iteration.
In this example, we will iterate numbers from a list using a for loop and calculate its
square. If we found a number greater than 10, we will not calculate its square and
directly jump to the next number.
Use the if condition with the continue statement. If the condition evaluates to true,
then the loop will move to the next iteration.
Ex:
numbers = [2, 3, 11, 7]
for i in numbers:
print('Current Number is', i)
# skip below statement if number is greater than 10
if i > 10:
continue
square = i * i
print('Square of a current number is', square)
Output:
Current Number is 2
Square of a current number is 4
Current Number is 3
Square of a current number is 9
Current Number is 11
Current Number is 7
Square of a current number is 49
Pass Statement in Python
➢ In Python, the pass keyword is used to execute nothing; it means, when we don't
want to execute code, the pass can be used to execute empty.
➢ The difference between the comments and pass is that, comments are entirely
ignored by the Python interpreter, where the pass statement is not ignored.
➢ Suppose we have a loop, and we do not want to execute right this moment, but we
will execute in the future. Here we can use the pass.
Ex:
for i in [12,3,4,5]:
if i==4:
pass
print('this is pass block',i)
print(i)
Ex:
# pass is just a placeholder for
# we will adde functionality later.
values = {'P', 'y', 't', 'h','o','n'}
for val in values:
pass
INDEXING IN STRINGS
➢ Indexing: Indexing is used to obtain individual elements from an ordered set data.
➢ Individual elements are accessed directly by specifying the string name followed by a
number in square brackets ([]).
➢ String indexing in Python is zero-based: the first character in the string has index 0,
the next has index 1, and so on. The index of the last character will be the length of
the string minus one.
➢ Negative indexing moves in reverse direction of string and starts from -1.
-6 -5 -4 -3 -2 -1
R G M C E T
0 1 2 3 4 5
Name = "RGMCET"
>>> Name[0]
'R'
>>> Name[3]
'C'
>>> Name[-1]
'T'
>>> Name[-4]
'M'
>>> Name[6]
Traceback (most recent call last):
File "<pyshell#22>", line 1, in <module>
Name[6]
IndexError: string index out of range
>>> Name[-7]
Traceback (most recent call last):
File "<pyshell#23>", line 1, in <module>
Name[-7]
IndexError: string index out of range
>>>
Note
Form of indexing syntax that extracts substrings from a string, known as string slicing.
-6 -5 -4 -3 -2 -1
R G M C E T
0 1 2 3 4 5
‘TEC’>>> Name[-6:-1:2]
‘RME’
>>> Name[-2:-6]
‘ ‘ # null string, We can solve this problem by
step value negative
>>> Name[-2:-6:-1]
‘ECMG’
Name [3] ='S'
Traceback (most recent call last):
File "<pyshell#40>", line 1, in <module>
Name [3] ='S'
TypeError: 'str' object does not support item assignment
>>> Name = "RGMCET"
>>> Name = Name.replace('C','S')
>>> Name
'RGMSET'
>>>
STRING METHODS
Welcome to python
WELCOME TO PYTHON
welcome to python
Welcome To Python
WELCOME tO pYTHON
['welcome', 'To', 'Python']
a = "hello"
print(a.center(10, '&')) #Here the width is 10 and the string length is
5, so now we need to fill the remaining width(10 - 5 = 5) with '&'
special character.
b = "Python"
print(b.center(10, '*'))
&&hello&&&
**Python**
2.Methods Of Strings
a = "happy married life happy birthday birthday baby"
#returns the number of occurrences of substring in particular string.
If the substring does not exist, it returns zeroo
print(a.count('happy'))
a = "java is simple"
print(a.replace('java' ,'Python'))
2
Python is simple
java is simple
b = '.'
List_1 = ['www', 'rgmcet', 'com']
#returns a string concatenated with the elements of an iterable. (Here
“List_1” is the iterable)
print(b.join(List_1))
www.rgmcet.com
string = 'Python'
print(string.isupper()) # used to check whether all characters
(letters) of a string are uppercase or not.
print(string.islower()) #used to check whether all characters (letters)
of a string are lowercase or not.
print(string.isalpha()) #used to check whether a string consists of
alphabetic characters only or not.
print(string.isalnum()) #used to check whether a string consists of
False
False
True
True
string_1 ='56789'
string_2 = 'rgm03'
print(string_1.isdigit()) #used to check whether a string consists of
digits only or not. If the string contains only digits then it returns
True, otherwise False.
print(string_2.isdigit())
True
False
False
True
True
False
4. Methods of strings
#startswith(substring)
string = 'department of mechanical engineering'
print(string.startswith('m')) #checks whether the main string starts
with given sub string. If yes it returns True, otherwise False.
print(string.endswith('g')) # checks whether the string ends with the
substring or not.
print(len(string)) # returns the length of the string or to find the
number of characters present in the string
print(min(string)) # returns the minimum character in the string
print(max(string)) # returns the maximum character in the string
print(string.find('of')) #returns the index of the first occurrence of
the substring, if it is found, otherwise it returns -1
False
True
36
t
11
31
11
6
UNIT-III
DATA STRUCTURES
SYLLABUS
Lists: Operations on List, important methods used on list. List comprehensions
Tuples: Operations on tuples, important methods used on tuple
Sets: Operations on sets, important methods used on set
Dictionaries: Operations on Dictionaries, important methods used on dictionaries.
LIST
• List is a collection of items (Python objects)
• The purpose of the list is, to group up the things, which fall under the same category
Examples
Characteristics
• Even though the list principle suggests homogeneous data items in it, it is not
mandatory and still allowed to have different types (Heterogeneous data) which
makes it a most powerful tool in Python
• Growable in nature, i.e based on our requirement we can increase or decrease the
size.
Applications:
• If the content is keep on changing, better to opt for list type. For example, Youtube
comments or Facebook comments or Udemy reviews (which are keep on changing
day by day).
• Used in JSON (Java Script Object Notation) format to transmit data between web
application and server.
• Used in Databases
• Create a list: Create a comma separated list of elements and assign to variable.
• Indexing: Accessing the list items.
• Slicing : accessing the part of the list elements.
• Concatenation: adding the lists
• Updating : Updating the list elements
• Membership: To check the membership of element.
• Comparison
• Repetition
[]
<class 'list'>
[0, 2, 4, 6, 8]
Note:
Sometimes we can take list inside another list, such type of lists are called nested
lists. [10, 20, [30, 40]]
Repetition Operator:
The repetition operator enables the list elements to be repeated multiple times.
list_1 = [1, 2, 3, 4]
list_3 =list_1*3
print(list_3)
[1, 2, 3, 4, 1, 2, 3, 4, 1, 2, 3, 4]
Concatenation:
[1, 2, 3, 4, 5, 6, 7, 8]
Membership:
True
True
Length:
list_1 = [1, 2, 3, 4]
list_2= [5, 6, 7, 8]
print(list_1 == list_2)
print(list_1 != list_2)
print(list_1>list_2)# it is based on the first element
print(list_1<list_2)
list_1 = [1, 2, 3, 4]
list_2= [1, 6, 7, 8]
print(list_1>list_2)
# it is based on the second element, if the first element in list is sa
me
print(list_1<list_2)
print(list_1>=list_2)
print(list_1<=list_2)
False
True
False
True
False
True
False
True
Updating
list = [1,4,8,9,13]
list[1] = 2
print(list)
[1, 2, 8, 9, 13]
• We can access elements of the list either by using index or by using slice operator (:)
• Indexing: Indexing is used to obtain individual elements. List follows zero based index.
ie index of first element is zero and supports both positive and negative indexing.
1. By using Indexing
list=[10,20,30,40]
print(list[0]) #10
print(list[-1]) #40
print(list[-4]) #10
print(list[10]) #IndexError: list index out of range
10
40
10
-----------------------------------------------------------------------
IndexError Traceback (most recent call last)
<ipython-input-33-714b2c12ce65> in <module>()
3 print(list[-1]) #40
4 print(list[-4]) #10
----> 5 print(list[10]) #IndexError: list index out of range
list = [10,20,[30,40]]
print(list[2])
print(list[2][1])
[30, 40]
40
List vs mutability:
0
1
2
3
4
5
6
7
8
9
10
0
1
2
3
4
5
6
7
8
9
10
0
2
4
6
8
10
* Function:
* Method:
In other words, if you are calling any function with object reference is called as method.
• all(): Returns True if all the items in the list has a True value.
• any() : Returns True if even one item in the list has a True value.
• enumerate(): Returns an enumerate object consisting of the index and value of all
items of list as a tuple pair.
• len(): This function calculates the length i.e., the number elements in the list.
• list(): This function converts an iterable (tuple, string, set, dictionary) to a list
▪ max(): This function returns the item with the highest value from the list
▪ min():This function returns the item with the lowest value from the list.
▪ sorted(): This function returns a sorted result of the list, with the original list
unchanged.
• sum():This function returns the sum of all elements in the list. This function works only
on numeric values in the list and will error out if the list contains a mix of string and
numeric values.
*append(x):
* extend(iterable):
* insert(index, item):
* remove(element):
Error if the item doesn't exist with the value element in list
* pop(), pop(index):
Removes an item at the given position specified by index
Removes and returns the last element if index is not specified
If an invalid index is specified, then an IndexError is thrown
* count(x):
If the parameter reverse = True, then the list is sorted in place in descending order
* reverse():
* copy()
Equivalent to a[:]
index(): function: returns the index of first occurrence of the specified item
n=[10,20,30,40]
print(len(n))
n=[1,2,2,2,2,3,3]
print(n.count(1))
print(n.count(2))
print(n.count(3))
print(n.count(4))
1
4
2
0
n=[1,2,2,2,2,3,3]
print(n.index(1)) # 0
print(n.index(2)) # 1
print(n.index(3)) # 5
#print(n.index(4)) #If the specified element not present in the list th
en we will get ValueError.
0
1
5
[(0, 1), (1, 2), (2, 2), (3, 2), (4, 2), (5, 3), (6, 3)]
1. append() function:
We can use append() function to add new item ((which can be any Python object, such as
an Integer, String, another List, Dictionary or anything else.) at the end of the existing
python list.
* Syntax: list.append(item)
*append() function only takes a single argument that is the item which is needed to be
added or appended at the end of the list.
- Obviously, this method would not have anything to return, so it simply returns None.
list=[]
list.append("A")
list.append("B")
list.append("C")
print(list)
#Eg: To add all elements to list upto 100 which are divisible by 10
list=[]
for i in range(101):
if i%10==0:
list.append(i)
print(list)
[0, 10, 20, 30, 40, 50, 60, 70, 80, 90, 100]
#Another way
list= []
for i in range(0,101,10):
list.append(i)
print(list)
[0, 10, 20, 30, 40, 50, 60, 70, 80, 90, 100]
2. insert() function:
* The list.insert() method is used to insert an item at a particular index into a given Python
List. The new item to be inserted and the index at which it is to be inserted has to be
provided as the second and first arguments to this method respectively.
list.insert(index, item)
n=[1,2,3,4,5]
n.insert(1,888)
print(n)
print()
[1, 888, 2, 3, 4, 5]
n=[1,2,3,4,5]
n.insert(10,777)
n.insert(-10,999)
print(n)
print(n.index(777))
print(n.index(999))
[999, 1, 2, 3, 4, 5, 777]
6
0
Note:
If the specified index is greater than max index then element will be inserted at last
position.
#If the specified index is smaller than min index then element will be inserted at first
position
3. extend() function:
To add all items of one list to another list,we use extend() method.
list1.extend(list2)
order1=["Chicken","Mutton","Fish"]
order2=["RC","KF","FO"]
order1.extend(order2)
print(order1)
print(order2)
numbers_list = [1,2,3,4,5]
numbers_tuple = (6,7,8,9,10)
numbers_set = {11,12,13,14,15}
print("Original List",numbers_list)
#Extending List using tuple
numbers_list.extend(numbers_tuple)
print("Extended List:",numbers_list)
#Extending List using set
numbers_list.extend(numbers_set)
print("Extended List:",numbers_list)
order1=["Chicken","Mutton","Fish"]
order2=["RC","KF","FO"]
order3 = order1 + order2
print(order1)
print(order2)
print(order3)
order=["Chicken","Mutton","Fish"]
order.extend("Mushroom") # It adds every character as a single element
to the list
print(order)
['Chicken', 'Mutton', 'Fish', 'M', 'u', 's', 'h', 'r', 'o', 'o', 'm']
Explanation :
Here, 'Mushroom' is a string type, in this string 8 elements are there. These elements are
added seperately.
numbers_list = [1,2,3,4,5]
numbers_list_2 = ["A","B","C","D","E"]
numbers_tuple = (6,7,8,9,10)
numbers_set = {11,12,13,14,15}
print("Original List",numbers_list)
#Concatenating numbers_list_2 into numbers_list
numbers_list = numbers_list + numbers_list_2
#OR
#numbers_list += numbers_list_2
#Extending List using tuple
numbers_list += numbers_tuple
print("Extended List:",numbers_list)
#Extending List using set
numbers_list += numbers_set
print("Extended List:",numbers_list)
4. remove() function:
We can use this function to remove specified item from the list.
If the item present multiple times then only first occurrence will be removed
list.remove(itemToBeRemoved)
n=[10,20,10,30]
n.remove(10)
print(n)
If the specified item not present in list then we will get ValueError
5. pop() function:
This is only function which manipulates list and returns some element.
* The pop() method of the Python List Object is used to remove any item from the list by
using its index. This method also returns the item so removed.
removedItem = list.pop(itemIndex)
n=[10,20,30,40]
print(n.pop())
print(n.pop())
print(n)
40
30
[10, 20]
#A Python List
items = ["Pen", "Whiteboard", "Tablet", "Smartphone", "Cleaner"]
#Removing the item at Index 2 i.e. "Tablet"
removedItem = items.pop(2)
#Printing the so returned Removed item
print("Removed Item:",removedItem)
#Negative Indexing Removals
#Another Python List
items = ["Laptop","Bottle","Stick","Speaker","Rubber"]
#Removing the 3rd Last item from the List
#i.e. "Stick"
#using Negative Index -3
removedItem = items.pop(-3)
print("Removed Item", removedItem)
-----------------------------------------------------------------------
IndexError Traceback (most recent call last)
<ipython-input-51-ff7624fa208d> in <module>()
3 #Passing Index Out of the Range of the List
4 #Will raise IndexError: pop index out of range
----> 5 numbers.pop(8)
Note:
1. pop() is the only function which manipulates the list and returns some value
3. In general we can use pop() function to remove last element of the list. But we can use
to remove elements based on index.
list.reverse()
n=[10,20,30,40]
n.reverse()
print(n)
2. sort() function:
In list by default insertion order is preserved. If you want to sort the elements of list
according to default natural sorting order then we should go for sort() method.
list.sort(key=keyFunction, reverse=True/False)
n=[20,5,15,10,0]
n.sort()
print(n)
s=["Dog","Banana","Cat","Apple"]
s.sort()
print(s)
Note:
To use sort() function, compulsory list should contain only homogeneous elements,
otherwise we will get TypeError.
n=[20,10,"A","B"]
n.sort()
print(n)
-----------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-32-76d0c10ed9e7> in <module>()
1 n=[20,10,"A","B"]
----> 2 n.sort()
3 print(n)
n=['20',"B",'10',"A"]
n.sort()
print(n)
How to sort the elements of list in reverse of default natural sorting order:
Alternate Way :
We can sort according to reverse of default natural sorting order by using reverse = True
argument.
n=[40,10,30,20]
n.sort()
print(n) #[10,20,30,40]
n.sort(reverse=True) # Reverse Sort a list i.e. sorting the list in the
Descending order, we just have to specify the argument reverse of the m
ethod sort() as True
print(n) #[40,30,20,10]
n.sort(reverse=False)
print(n) #[10,20,30,40
s=["Dog","Banana","Cat","Apple"]
s.sort(reverse= True) # reverse of Alphabetical order
print(s)
In the below example, we have a list of some strings and each of these strings has a
different length. So, here we’re sorting the list according to the length of the strings in
ascending as well as in the descending order.
demo = ["aaaaa","aa","a","aaaaaa","aaaa","aaaaaaa","aaa"]
print("Initial Ordeer: " + str(demo))
demo.sort(key = len)
print("Small To Large: " + str(demo))
demo.sort(key = len, reverse = True)
print("Large To Small: " + str(demo))
Here also we’ll make use fo the key argument but to this argument, we’ll provide our own
defined custom function containing the logic of sorting.
I’ve taken a Python List that contains tuples as the items. Each tuple contains 3 numbers.
The list is now sorted according to the ascending order of the sum of the numbers in each
tuple item.
alist = [(12, 0, 9),(11, 1, 2), (12, 5, 3), (5, 3, 0), (3, 4, 8)]
print("Original Order: " + str(alist))
def tupleSum(element):
return sum(element)
alist.sort(key = tupleSum)
print("Ascending Order: " + str(alist))
alist.sort(key = tupleSum, reverse = True)
print("Descending Order: " + str(alist))
Original Order: [(12, 0, 9), (11, 1, 2), (12, 5, 3), (5, 3, 0), (3, 4, 8)]
Ascending Order: [(5, 3, 0), (11, 1, 2), (3, 4, 8), (12, 5, 3), (12, 0, 9)]
Descending Order: [(12, 0, 9), (12, 5, 3), (3, 4, 8), (11, 1, 2), (5, 3, 0)]
Note:
To use sort() function, compulsory list should contain only homogeneous elements,
otherwise we will get TypeError.
n=[20,10,"A","B"]
n.sort()
print(n)
-----------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-55-76d0c10ed9e7> in <module>()
1 n=[20,10,"A","B"]
----> 2 n.sort()
3 print(n)
The method clear() is used to remove all the items from a given Python List. This method
does not delete the list but it makes the list empty.
Syntax
list.clear()
#A list containing some items
items = ["Copy","Pen",10, 1.5, True, ('A','B')]
print("Initial List:",items)
#Clearing all the list items
items.clear()
print("Empty List:",items)
Example. Deleting all list items using del keyword & Slicing Operator
* The code for the following example is exactly the same as above. The difference is just
that we’ve used the del keyword and the slicing operator to delete all the items from the
list instead of the list.clear() method.
#A list containing some items
items = ["Copy","Pen",10, 1.5, True, ('A','B')]
print("Initial List:",items)
#Clearing all the list items
#Using del keyword
del items[:]
print("Empty List:",items)
Built-in functions
print(all([' ', ',', '1', '2'])) # only 0 and false are treated as not
true
True
print(all(['', 0, 1]))
False
print(any([' ', ',', '1', '2']))# returns true if there is at least one True (any
thing other than 0 or False) in the list
True
[(0, 'a'), (1, 'b'), (2, 'c'), (3, 'd'), (4, 'e')]
print(max([1, 2, 3, 4, 5]))
print(min([1, 2, 3, 4, 5]))
[1, 1, 3, 4, 5, 7, 9, 27]
print(sum([1, 5, 3, 4, 7, 9, 1, 27]))
print(sum([1, 3, 5, 'a', 'b', 4, 6, 7]))
57
-----------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-74-cb4452331f6b> in <module>()
1 print(sum([1, 5, 3, 4, 7, 9, 1, 27]))
----> 2 print(sum([1, 3, 5, 'a', 'b', 4, 6, 7]))
* The process of giving another reference variable to the existing list is called aliasing.
* list1 = [1,2,3,4,5]
* list2 = list1
* list1 = [1,2,3,4,5]
* list2 = list1
In the above code, we have a list of 5 items. In the second line, we’ve used the = operator,
thinking it will create a copy of the list into the list2 variable. But is it like that?
list2 will not contain a copy of the list1, rather the list2 will only be a new reference variable
for the list1. It means the list of 5 items is now having two names, list1 and list2. In other
words, it does not duplicate the list. Any changes made to list1 will also be reflected in
list2 because the list1 and list2 both point to the same memory address.
* Cloning :The process of creating exactly duplicate independent object is called cloning.
The list.copy() method is used to create a copy of the list into a new variable.
Now many of you might be questioning, why we need a method to copy a list into a new
variable when we can simply do it with the assignment operator = (equals to)?
Hence, we need the list.copy() method to actually create a new copy of a given list.
list_copy = list.copy()
#List1
list1 = ["Gurmeet","Jaskaran","Akshit","Sahil"]
print("Original List:",list1)
print("Copied List with Changes",list2)
The Slicing operator can also be used to create a fresh new copy of a Python List and this
is illustrated in the following example.
#List1
list1 = ["Gurmeet","Jaskaran","Akshit","Sahil"]
#Copying list1 into list2
#Using Slicing Operator
list2 = list1[:]
#Making some changes in only list2
list2.append("Sheila")
print("Original List:",list1)
print("Copied List with Changes",list2)
INTRODUCTION TO TUPLES:
• Tuples are like lists, but their elements are fixed; that is, once a tuple is created, you
cannot add new elements, delete elements, replace elements, or reorder the
elements in the tuple.
• The major differences between the two are: Lists are enclosed in square brackets [ ]
and their elements and size can be changed (mutable), while tuples are enclosed in
parentheses () and their elements cannot be changed (immutable).
• Note: Since a tuple is immutable, iterating through a tuple is faster than with a list.
This gives a slight performance improvement. Once a tuple is defined, we cannot
add elements in it or remove elements from it.
• A tuple can be converted into a list so that elements can be modified and converted
back to a tuple.
• Tuple support both +ve and -ve index. +ve index means forward direction(from left
to right) and -ve index means backward direction(from right to left).
Characteristics
• Maintains the order of the data insertion
• Tuples are immutable
• Tuples can contain the heterogeneous data
• Tuples allows duplicate data
Applications:
• If the content is fixed, better to opt for tuple type.
• For example, In Banks, account type - Only 2 values are there, 1. Savings 2.
Current At runtime account types never going to change throughout Bank Project.
So, to represent bank account types, better to go for the tuple concept. Some other
Examples, Where allowed inputs are fixed (Best suitable type is tuple):
b. In the Metro stations also, If you want to get the tickets, you have to insert
either 10/- note or 20/- note only
tuple_1 =5,6, 8, 9
tuple_2 =(5, 6, 8, 9)
print(tuple_1)
print(tuple_2)
print(type(tuple_1))
print(type(tuple_2))
(5, 6, 8, 9)
(5, 6, 8, 9)
<class 'tuple'>
<class 'tuple'>
# empty tuple
tuple =()
print(tuple)
print(type(tuple))
()
<class 'tuple'>
Note:
We have to take special care about single valued tuple. compulsory the value should
ends with comma, otherwise it is not treated as tuple.
tuple = (10)
print(tuple)
print(type(tuple))
10
<class 'int'>
tuple = (10,)
print(tuple)
print(type(tuple))
(10,)
<class 'tuple'>
tuple = (10,20,30,)
print(tuple)
print(type(tuple))
if you have any sequence (i.e., string, list, range etc.,) which can be easily converted into
a tuple by using tuple() function.
list=[10,20,30]
t=tuple(list)
print(t)
print(type(t))
t=tuple(range(10,20,2))
print(t)
print(type(t))
t = tuple('engineering')
print(t)
print(type(t))
('e', 'n', 'g', 'i', 'n', 'e', 'e', 'r', 'i', 'n', 'g')
<class 'tuple'>
10
60
-----------------------------------------------------------------------
IndexError Traceback (most recent call last)
<ipython-input-13-ba1aec3992ff> in <module>()
3 print(t[0]) #10
4 print(t[-1]) #60
----> 5 print(t[100]) #IndexError: tuple index out of range
t= tuple('engineering')
print(t[0])
print(t[1:5:1])
print(t[-2:-5:-1])
e
('n', 'g', 'i', 'n')
('n', 'i', 'r')
Tuple vs immutability:
Once we creates tuple,we cannot change its content. Hence tuple objects
are immutable.
t=(10,20,30,40)
t[1]=70
print(t)
-----------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-16-e0f1d773bd10> in <module>()
1 t=(10,20,30,40)
----> 2 t[1]=70
3 print(t)
t1 = 10,20,30,40
t2 = 10,20,30,40
t3 = t1 + t2 # because list and tuple allow duplicates, so you will get
all the elements
print(t3)
#Iterating a Tuple
aTuple = ("Tutorial","Lesson","Teaching", 21)
for item in aTuple:
print(item)
Tutorial
Lesson
Teaching
21
Membership operators
• in and not in can be used to check if a particular item exists in the tuple or not.
a = (2, 3, 4, 5, 6, 7, 8, 9, 10)
print(5 in a)
print(100 in a)
print(2 not in a)
True
False
False
Comparison operators
Returns True if all elements in both tuples are same otherwise returns false.
a = (2, 3, 4, 5, 6, 7, 8, 9, 10)
b = (2, 3, 4)
print(a == b)
print(a != b)
print(a < b)
print(a > b)
print(a <= b)
print(a >= b)
False
True
False
True
False
True
#all(): Returns True if all the items in the tuple has a True value
print(all((' ', ',', '1', '2')))
True
#any(): Returns True if even one item in the tuple has a True value
print(any((' ', ',', '1', '2')))
True
((0, 1), (1, 2), (2, 3), (3, 4), (4, 5), (5, 6))
# len(): This function calculates the length i.e., the number elements
in the tuple
x = (1, 2, 3, 4, 5, 6)
print(len(x))
# max(): This function returns the item with the highest value in the
tuple
print(max((1, 2, 3, 4, 5, 6)))
t = ('engineering') # based on unicode values these functions will
work.
print(max(t))
6
r
# min(): This function returns the item with the lowest value in the
tuple
print(min((1, 2, 3, 4, 5, 6)))
t = ('engineering') # based on unicode values these functions will
work.
print(min(t))
1
e
[1, 1, 3, 4, 5, 7, 9, 27]
(1, 5, 3, 4, 7, 9, 1, 27)
# sum(): This function returns the sum of all elements in the tuple.
# This function works only on numeric values in the tuple and will
error out if the tuple contains a mix of string and numeric values.
print(sum((1, 5, 3, 4, 7, 9, 1, 27)))
print(sum((1, 'hi', 3, 4, 7, 'how', 1, 27)))
57
-----------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-34-b7b5c79dffbd> in <module>()
2 # This function works only on numeric values in the tuple and
will error out if the tuple contains a mix of string and numeric
values.
3 print(sum((1, 5, 3, 4, 7, 9, 1, 27)))
----> 4 print(sum((1, 'hi', 3, 4, 7, 'how', 1, 27)))
-----------------------------------------------------------------------
ValueError Traceback (most recent call last)
<ipython-input-38-23421a9fb8f3> in <module>()
2 t=(10,20,10,10,20)
3 print(t.index(10)) # 0
----> 4 print(t.index(30))
a=10
b=20
c=30
d=40
t=a,b,c,d
print(t) #(10, 20, 30, 40)
Here a,b,c,d are packed into a tuple t. This is nothing but tuple packing.
a = 10
b = 20
c = 30
d = 40
t =[a,b,c,d]
print(type(t))
print(t)
<class 'list'>
[10, 20, 30, 40]
a = 10
b = 20
c = 30
d = 40
t ={a,b,c,d} # for 'set' order is not important
print(type(t))
print(t)
<class 'set'>
{40, 10, 20, 30}
a = 10
b = 20
c = 30
d = 40
t ='a,b,c,d'
print(type(t))
print(t)
<class 'str'>
a,b,c,d
Tuple unpacking :
t=(10,20,30,40)
a,b,c,d=t
print("a=",a,"b=",b,"c=",c,"d=",d)
a= 10 b= 20 c= 30 d= 40
t=[10,20,30,40]
a,b,c,d=t
print("a=",a,"b=",b,"c=",c,"d=",d)
a= 10 b= 20 c= 30 d= 40
t={10,20,30,40}
a,b,c,d=t
print("a=",a,"b=",b,"c=",c,"d=",d)
a= 40 b= 10 c= 20 d= 30
t='abcd'
a,b,c,d=t
print("a=",a,"b=",b,"c=",c,"d=",d)
a= a b= b c= c d= d
Note:
At the time of tuple unpacking the number of variables and number of values should be
same, otherwise we will get ValueError
t=(10,20,30,40)
a,b,c=t
print("a=",a,"b=",b,"c=",c)
-----------------------------------------------------------------------
ValueError Traceback (most recent call last)
<ipython-input-52-42c848936d4d> in <module>()
1 t=(10,20,30,40)
----> 2 a,b,c=t
3 print("a=",a,"b=",b,"c=",c)
Tuple Comprehension
• Here we are not getting tuple object and we are getting generator
object.
<class 'generator'>
1
4
9
16
25
Introduction to Set
• A set is a mutable data type and We can add or remove items / elements from it.
• The set data type is, as the name implies, a mathematical set. we can perform
operations like union, intersection, difference and symmetric difference.
• Set does not allow duplicates. Set does not maintain order. This is because the
placement of each value in the set is decided by an arbitrary index produced by the
hash() function.
• Internally uses a hash table. Values are translated to indices of the hash table using
the hash() function. When a collision occurs in the hash table, it ignores the element.
▪ This explains, why sets unlike lists and tuples can't have multiple occurrences of the
same element. type() of set is 'set'.
• index and slicing concept is not applicable
• A set is represented with { }.
Characteristics:
• A set is a mutable data type and We can add or remove items / elements from it.
• The elements in a Set cannot be changed (immutable). Insertion order is not
preserved.
• Duplicates are not allowed.
• Indexing and slicing not allowed for the set.
• Heterogeneous elements are allowed.
s = {10}
print(type(s))
print(s)
<class 'set'>
{10}
numset = {1, 2, 3, 4, 5, 3, 2}
print(numset)
{1, 2, 3, 4, 5}
<class 'set'>
-----------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-3-72e199601121> in <module>()
1 s = {30,40,10,5,20} # in the output order not preserved
2 print(type(s))
----> 3 print(s[0])
<class 'set'>
----------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-4-3077da98f87a> in <module>()
1 s = {30,40,10,5,20} # in the output order not preserved
2 print(type(s))
----> 3 print(s[0:6])
list = [10,20,30,40,10,20,10]
s=set(list)
print(s)
s=set(range(10))
print(s)
{0, 1, 2, 3, 4, 5, 6, 7, 8, 9}
s = set('mechanical')
print(s)
Note:
• While creating empty set we have to take special care. Compulsory we should use
set() function.
s = {}
print(type(s))
<class 'dict'>
set()
<class 'set'>
#set of fruits
fruits = {'Apple', 'Banana', 'Cherry', 'Dates'}
Apple
Cherry
Dates
Banana
Note. You can observe in the output that the items are looped through in a different order
than they actually defined set order. This again shows the unindexed and unordered
property of the set.
True
False
False
True
The union of two sets is the set of all the elements of both the sets without duplicates. You
can use the union() method or the | syntax to find the union of a Python set.
A = {1, 2, 3, 4, 5, 6}
B = {4, 5, 6, 7, 8, 9}
A ⋃ B: {1, 2, 3, 4, 5, 6, 7, 8, 9}
A ⋃ B: {1, 2, 3, 4, 5, 6, 7, 8, 9}
B ⋃ A: {1, 2, 3, 4, 5, 6, 7, 8, 9}
2. Set Intersection
The intersection of two sets is the set of all the common elements of both the sets. You
can use the intersection() method of the & operator to find the intersection of a Python set.
A = {1, 2, 3, 4, 5, 6}
B = {4, 5, 6, 7, 8, 9}
3. Set Difference
If there are two sets, A and B, then the difference of the set B from set A i.e. A - B will be
a set containing all the items that are only present in set A and not in set B. Similarly, the
difference of the set A from set B i.e. B - A will be a set containing all the items that are
only present in set B and not in set A.
A = {1, 2, 3, 4, 5, 6}
B = {4, 5, 6, 7, 8, 9}
{1, 2, 3}
{8, 9, 7}
{1, 2, 3}
{8, 9, 7}
The symmetric difference of the Set A and B is the set of all the elements that are not
common between the two sets. In other words, it is the set of all the elements of union
excluding the intersection elements.
To find out the set difference, you can either use the ^ operator or the
symmetric_difference() method on a given set. The code given below illustrates the usage
of this operator and method.
These are not so common, but they're useful in seeing how sets relate to others.
the a.isdisjoint(b) method return true if there are no common elements between sets a and
b
1. all() Function: This method returns a boolean value i.e. either True or False.
• If all the elements of the iterable object will be True or representing True, it will return
True.
• If at least one of the elements of the iterable object will be False or will indicate a False
value, it will return False.
print(all(list9))
print(all(list10))
print(all(check1))
print(all(check2))
print(all(check3))
print(all(check4))
True
True
False
False
False
False
False
False
True
False
True
True
True
True
False
True
True
False
As mentioned earlier as well, for any iterable containing no elements, this method all() will
always return True.
#Empty Dictionary
print(all({}))
#Empty list
print(all([]))
#Empty tuple
print(all(()))
#Empty String
print(all(""))
True
True
True
True
print(any(list8))
print(any(list9))
print(any(list10))
True
True
False
False
True
True
True
True
True
True
True
True
True
True
For any of the empty iterables whether it’s a Python List, Dictionary, Tuple or a String, this
method is going to return False always.
#Empty Dictionary
print(any({}))
#Empty list
print(any([]))
#Empty tuple
print(any(()))
#Empty String
print(any(""))
False
False
False
False
Syntax
vegetables = ["Potato","Tomato","Peas","Cauliflower"]
fruits = ("Mango","Apple","Papaya")
#Non-Numbered List
print(vegetables)
#Non-Numbered tuple
print(fruits)
#Enumerating List
vegetables = enumerate(vegetables)
#Enumerating Tuple, setting starting index as 5
fruits = enumerate(fruits,5)
#Converting Enumerable Object To Tuple
vegetables = tuple(vegetables)
#Converting Enumerable Object To List
fruits = list(fruits)
#Numbered vegetables Tuple
print(vegetables)
#Numbered fruits List
print(fruits)
-----------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-26-0b17de878f2a> in <module>()
12 vegetables = tuple(vegetables)
You can also do numbered iteration using the enumerate() function easily.
The following example illustrates the same.
cities = ["Ludhiana","Chandigarh","Amritsar","Jalandhar"]
print("List of Cities")
for city in cities:
print(city)
List of Cities
Ludhiana
Chandigarh
Amritsar
Jalandhar
(2, 'Amritsar')
(3, 'Jalandhar')
count = len(sequenceObject)
print(len(aEmptyList))
print(len(aList))
print(len(aTuple))
print(len(aRange))
0
5
3
94
#Byte Object
unicodeByte =
b'\xe0\xa4\xa8\xe0\xa4\xae\xe0\xa4\xb8\xe0\xa5\x8d\xe0\xa4\x95\xe0\xa4\
xbe\xe0\xa4\xb0'
print(len(aByteObject))
print(len(unicodeByte))
0
0
21
25
21
0
0
0
2
2
2
max()
min()
sorted()
It returns a new list that contains the set elements in sorted order.
sum()
1. add(x):
Adds item x to the set
s={10,20,30}
s.add(40); # ';' is optional for python statements
print(s)
s={10,20,30}
s.add('mechanical'); # ';' is optional for python statements
print(s)
2. update(x, y, z)
It updates the set after doing union of itself with another set.
* Arguments are not individual elements and these are Iterable objects like List,range etc.
* All elements present in the given Iterable objects will be added to the set
s={10,20,30}
s.update('mechanical'); # ';' is optional for python statements
print(s)
{'n', 10, 'h', 'i', 'c', 'a', 'm', 20, 'e', 'l', 30}
s={10,20,30}
l=[40,50,60,10]
s.update(l,range(5))
print(s)
s={10,20,30}
l=[40,50,60,10]
s.update(l,range(5),100)
print(s)
-----------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-36-96e519440e16> in <module>()
1 s={10,20,30}
2 l=[40,50,60,10]
----> 3 s.update(l,range(5),100)
4 print(s)
s={10,20,30}
l=[40,50,60,10]
s.update(l,range(5),'100')
print(s)
s={10,20,30}
l=[40,50,60,10]
s.update(l,range(5),'mechanical')
print(s)
{0, 1, 2, 3, 4, 10, 'c', 20, 30, 40, 50, 'm', 60, 'h', 'a', 'i', 'n',
'e', 'l'}
s =set()
s.update(range(1,10,2),range(0,10,2))
print(s)
{0, 1, 2, 3, 4, 5, 6, 7, 8, 9}
We can use add() to add individual item to the Set,whereas we can use update() function
to add multiple items to Set.
add() function can take only one argument where as update() function can take any
number of arguments but all arguments should be iterable objects like strings, lists, tuple,
dictionary, set etc.
3. copy():
Returns copy of the set. It is cloned object (Backup copy)
s={10,20,30}
s1=s.copy()
print(s1)
print(s)
4. pop():
It removes and returns some random element from the set.
s={40,10,30,20}
print(s)
print(s.pop())
print(s.pop())
print(s.pop())
print(s)
print(s.pop())
print(s) # empty set
print(s.pop())
----------------------------------------------------------------------
KeyError Traceback (most recent call last)
<ipython-input-41-e74fb62025b2> in <module>()
7 print(s.pop())
8 print(s) # empty set
----> 9 print(s.pop())
5. remove(x):
It removes specified element from the set.
If the specified element not present in the Set then we will get KeyError.
s={40,10,30,20}
s.remove(30)
print(s) # {40, 10, 20}
s.remove(50) # KeyError: 50
-----------------------------------------------------------------------
KeyError Traceback (most recent call last)
<ipython-input-42-77437864d839> in <module>()
2 s.remove(30)
3 print(s) # {40, 10, 20}
----> 4 s.remove(50) # KeyError: 50
KeyError: 50
6. discard(x):
It removes the specified element from the set. If the specified element not present in the
set then we won't get any error.
s={10,20,30}
s.discard(10)
print(s) #{20, 30}
s.discard(50)
print(s) #{20, 30}
{20, 30}
{20, 30}
7.clear():
To remove all elements from the Set.
s={10,20,30}
print(s)
s.clear()
print(s)
{10, 20, 30}
set()
Set Comprehension
Set comprehension is possible.
Syntax: # s = {expression for x in sequence condition}
s = {x*x for x in range(6)}
print(s)
{0, 1, 4, 9, 16, 25}
s={2**x for x in range(2,10,2)}
print(s)
{16, 256, 64, 4}
Introduction to dictionary
• We can use List,Tuple and Set to represent a group of individual objects as a single
entity.
• If we want to represent a group of objects as key-value pairs then we should go for
Dictionary.
• Dictionary is an unordered collections of unique values stored in key and value
pairs.
• General usage of dictionaries is to store key-value pairs like :
– Employees and their wages
– Countries and their capitals
– Commodities and their prices
– Students roll numbers and their names
– Mobile numbers and their address
– ipaddress and its domain name
• In a dictionary, the keys should be unique, but the values can change. For example,
the price of a commodity may change over time, but its name will not change.
• Immutable data types like number, string, tuple etc. are used for the key and any
data type is used for the value.
• Dictionaries are represented by curly braces {}.
• The key-value pairs are represented as key : value.
• For example, daily temperatures in major cities are mapped into a dictionary as {
"Hyderabad" : 27 , "Chennai" : 32 , "Mumbai" : 40 }.
Overview of Operations
• The typical operations that can be performed on a dictionary are:
– Adding elements i.e., Key:Value pairs.
– Accessing elements using the Key with the Index operator [] or using get()
method.
details = {}
#adding new items
details['department'] = 'mechanical'
details['college'] = 'rgmcet'
details['established'] = 1995
print(details)
#changing values
details['department'] = 'computer science'
print(details)
{'department': 'mechanical', 'college': 'rgmcet', 'established': 1995}
{'department': 'computer science', 'college': 'rgmcet', 'established':
1995}
KeyError: 'State'
del details['College']
print(details)
{'Department': 'Mechanical Engineering', 'Established': 1995,
'College': 'RGMCET', 'Located at': 'Nandyal'}
{'Department': 'Mechanical Engineering', 'Established': 1995, 'Located
at': 'Nandyal'}
print("Dictionary:",marks)
2. copy()
• This method is used to create a shallow copy of a given Python
Dictionary.
dict1 = {
"Apple" : "Fruit",
"Banana" : "Fruit",
"Tomato" : "Vegetable",
"Papaya" : "Fruit",
"Potato" : "Vegetable"
}
dict2 = dict1.copy()
print("dict1:", dict1)
print("dict2:", dict2)
#Using copy() method for copying the dict1 to another variable dict1
dict2 = dict1.copy()
print("dict1:", dict1)
print("dict2:", dict2)
3.fromkeys(sequence, value)
The dict.fromkeys() method is used to create a new dictionary from a given sequence of
keys and a defined value by the user.
• newDict = dict.fromkeys(keys, value)
print(bio)
{'name': None, 'gender': None, 'age': None, 'website': None}
Creating a dictionary from a given sequence of Keys & a fixed Value
#Defined Sequence of Keys
keys = ["name", "gender", "age", "website"]
print(bio)
{'name': 'Hello', 'gender': 'Hello', 'age': 'Hello', 'website':
'Hello'}
4. d.get(key,defaultvalue)
• If the key is available then returns the corresponding value otherwise returns default
value.
bio = {
"name" : "Gurmeet Singh",
"gender" : "MALE",
"age" : 21,
"website" : "wtmatter.com"
}
5. items()
The method dict.items() returns a collection object containing the list of tuples such that
each tuple contains the dictionary items key & value pairs. Let’s say a dictionary contains
5 different key-value pairs. Then this method applied to this dictionary will return dict_list
collection object that will contain five tuples. Each of these tuples will contain exactly two
items, the first item will the key and the second will be the value associated with that
particular key.
#A Dictionary containing 4 items (key-value) pairs
bio = {
"name" : "Gurmeet Singh",
"gender" : "MALE",
"age" : 21,
"website" : "wtmatter.com"
}
print(items)
dict_items([('name', 'Gurmeet Singh'), ('gender', 'MALE'), ('age', 21),
('website', 'wtmatter.com')])
Modifying the dictionary after using the method items()
#A Dictionary containing 4 items (key-value) pairs
bio = {
"name" : "Gurmeet Singh",
"gender" : "MALE",
"age" : 21,
"website" : "wtmatter.com"
}
bio["country"] = "India"
#key exists
#only key argument passed
value = bio.setdefault("age")
#key exists
#both arguments passed
value = bio.setdefault("age", 25)
moreItems = {
"Japan" : "JPY",
"Brazil" : "BRL"
}
"Italy" : "EUR"
}
items.update(you = 4, Gurmeet = 5)
languages = {
0 : "English",
1 : "Hindi",
2 : "Punjabi",
3 : "Spanish",
4 : "French"
}
print("Values:", values)
Values: dict_values(['English', 'Hindi', 'Punjabi', 'Spanish',
'French'])
#dict_values gets updated if the dictionary is updated
#A Dictionary of languages
languages = {
0 : "English",
1 : "Hindi",
2 : "Punjabi",
3 : "Spanish",
4 : "French"
}
#Removing the Item from the dictionary using pop(), if the key exists
#A Dictionary of 5 items
items = {
"Brinjal (Eggplant)" : "Vegetable",
"Onion" : "Vegetable",
"Papaya" : "Fruit",
"Mango" : "Fruit",
"Radish" : "Vegetable"
}
print('before pop : ', items)
print("items:", items)
print("Returned Value:", value)
before pop : {'Brinjal (Eggplant)': 'Vegetable', 'Onion': 'Vegetable',
'Papaya': 'Fruit', 'Mango': 'Fruit', 'Radish': 'Vegetable'}
items: {'Brinjal (Eggplant)': 'Vegetable', 'Onion': 'Vegetable',
'Mango': 'Fruit', 'Radish': 'Vegetable'}
Returned Value: Fruit
#Working of pop() if the key does not exist
#A Dictionary of 5 items
items = {
"Brinjal (Eggplant)" : "Vegetable",
"Onion" : "Vegetable",
"Papaya" : "Fruit",
"Mango" : "Fruit",
"Radish" : "Vegetable"
}
print("items:", items)
print("Returned Value:", value)
-----------------------------------------------------------------------
KeyError Traceback (most recent call last)
<ipython-input-51-d120b4ccf672> in <module>()
11 #Popping the item with key Banana
12 #Item with this key not present in the dictionary
---> 13 value = items.pop("Banana")
14
15 print("items:", items)
KeyError: 'Banana'
#If the key does not exist in the dictionary but the default argument
is passed
#A Dictionary of 5 items
items = {
"Brinjal (Eggplant)" : "Vegetable",
"Onion" : "Vegetable",
"Papaya" : "Fruit",
"Mango" : "Fruit",
"Radish" : "Vegetable"
}
print("items:", items)
print("Returned Value:", value)
items: {'Brinjal (Eggplant)': 'Vegetable', 'Onion': 'Vegetable',
'Papaya': 'Fruit', 'Mango': 'Fruit', 'Radish': 'Vegetable'}
Returned Value: Fruit
bio["website"] = "wtmatter.com"
bio.popitem()
12.len()
This method returns the length.
dict = {'Name': 'Zara', 'Age': 7};
print ("Length : %d" % len (dict))
Length : 2
Dictionary Comprehensions
• Dictionary comprehension is a method for transforming one dictionary into another
dictionary. During this transformation, items within the original dictionary can be
conditionally included in the new dictionary and each item can be transformed as
needed.
• Dictionary Comprehensions return output in Dictionary format like (key : value) pairs
and Keys should be unique and each key has a respective value.
– {key : value for (key , value) in iterable}
squares={x:x*x for x in range(1,6)}
print(squares)
doubles={x:2*x for x in range(1,6)}
print(doubles)
{1: 1, 2: 4, 3: 9, 4: 16, 5: 25}
{1: 2, 2: 4, 3: 6, 4: 8, 5: 10}
# string of vowels
vowels = 'aeiou'
ip_str = ip_str.casefold()
count = {}.fromkeys(vowels,0)
if char in count:
count[char] += 1
print(count)
output: