SlideShare a Scribd company logo
Presented by
-------------------------
Dr Dileep Kumar M
UNIT- I
Contents Of UNIT-I
ï‚Ą Introduction
ï‚Ą History of Python Programming
ï‚Ą Features
ï‚Ą Applications
ï‚Ą Versions ,Flavors in Python
ï‚Ą Programming Modes
ï‚Ą Download & Install the Python in Windows & Linux
ï‚Ą How to set Python Environment in the System?
ï‚Ą Downloading and Installing Anaconda, Jupyter
Notebook & Spyder
ï‚Ą Python IDE - Jupyter Notebook Environment,
Spyder Environment
Introduction
ï‚Ą Python is a general purpose high level
programming language
ï‚Ą Interactive
ï‚Ą Interpreted
ï‚Ą Object Oriented & Scripting Language
History of Python
Centrum Wiskunde &
Informatica (CWI) is
the National Research
Institute for
Mathematics and
Computer Science in
the Netherlands.
20th
Guido van Rossum
Where it is derived from?
ï‚Ą Python is named after the BBC TV comedy
show Monty Python’s Flying Circus.
It is not named after the Python snake.
Python is derived from
ï‚Ą Functional Programming features from C
ï‚Ą OOPs features from C++
ï‚Ą Scripting language features from Perl
and Shell Script
ï‚Ą Modular Programming features from
Moudula-3
Python Features
Applications
ï‚Ą Data Science
ï‚Ą Artificial Intelligence
ï‚Ą Machine Learning
ï‚Ą Deep Learning
ï‚Ą Data Analysis
ï‚Ą NLP
ï‚Ą Neural Networks
ï‚Ą IOT
ï‚Ą Robotics
Existing Vs Python
Comparing Python to Other Languages
ï‚Ą Python code is typically 3-5 times
shorter than equivalent JAVA code
ï‚Ą It is often 5-10 times shorter than
equivalent C++ code
ï‚Ą And even shorter than C code
UNIT 1 PYTHON introduction and basic level
Programming Modes
ï‚Ą How to execute python program:
ï‚Ą By using Python Interpreter, we can execute python programs in 2
modes .they are:
1. Immediate mode
2. Script mode
ï‚Ą 1. Immediate mode: (in windows)
 In the mode, you type Python expressions into the Python Interpreter
window, and the interpreter immediately shows the results.
2. Script mode (in windows)
ï‚Ą we can open IDLE python then click on file, open new file
and we can write python program and save as filename.py.
After that ,to run this program press F5 button or click run
button click Run module.
Python Versions:
The implementation of Python was started in December 1989.
In February 1991, Guido Van Rossum published the code (labeled version 0.9.0) to alt.sources.
ï‚ȘPython 1.0 - January 1994
Python 1.0 was released with new features like lambda, map, filter, and reduce.
 Python 1.5 - December 31, 1997
 Python 1.6 - September 5, 2000
ï‚ȘPython 2.0 - October 16, 2000
Python 2.0 added new features such as list comprehensions, garbage collection systems.
 Python 2.1 - April 17, 2001
 Python 2.2 - December 21, 2001
 Python 2.3 - July 29, 2003
 Python 2.4 - November 30, 2004
 Python 2.5 - September 19, 2006
 Python 2.6 - October 1, 2008
 Python 2.7 - July 3, 2010 Python 2.7 is latest version of python2
ï‚Ș Python 3.0 - On December 3, 2008, Python 3.0 (also called "Py3K")
was released. It was designed to rectify the fundamental flaw of
the language.
 Python 3.1 - June 27, 2009
 Python 3.2 - February 20, 2011
 Python 3.3 - September 29, 2012
 Python 3.4 - March 16, 2014
 Python 3.5 - September 13, 2015
 Python 3.7.0 - June 27, 2018
 Python 3.7.1 - October 13, 2018
 Python 3.7.2 - December 24, 2015
 Python 3.7.3 - March 25, 2019
 Python 3.7.4 - July 8, 2019
Python 3 is not backward
compatible with Python 2.
Flavors of Python
ï‚Ą Types of Python compilers are referred
as flavors of Python.
1. CPython:
ï‚Ą 2. JPython:
ï‚Ą 3. IronPython:
ï‚Ą 4. PyPy:
Contd

ï‚Ą 5. Ruby Python:
ï‚Ą 6. Pythonxy:
ï‚Ą 7.Anaconda Python:
ï‚Ą 8. Stackless Python:
Download & Install the Python in Windows
https://www.python.org/downloads/
Installing Python in
Windows
ï‚Ą After downloading Run python-3.8.5. exe file. Install it and click
next.
ï‚Ą In window search button, type IDLE python, we get version of
python installed
python interpreter:
Installing Python in ubuntu
1. Open terminal via Ctrl+Alt+T or searching for “Terminal” from app
launcher.
2. Ubuntu 16.04 comes with both Python 2 and Python 3 by default.
3. If it is not there, install Python use following command :
sudo apt-get install python 3.8
4. To check updates use following command
sudo apt-get update
5. To know the versions of the python type following command:
Python Environment Setup in the
System
Interactive Mode and Scripting Mode of Programming
How to install Anaconda software in
windows
https://www.anaconda.com/distribution/
Anaconda is not an IDE, Anaconda is a Python distribution, (including for
commercial use and redistribution). It includes more than 400 of the most
popular Python packages for science, math, engineering, and data analysis.
UNIT 1 PYTHON introduction and basic level
UNIT 1 PYTHON introduction and basic level
Python IDE - Jupyter Notebook
Environment
UNIT 1 PYTHON introduction and basic level
Python IDE - Spyder Environment
Spyder Environment
Microsoft Visual Studio
ï‚Ą An integrated development environment (IDE) called
Microsoft Visual Studio is used to create software for
the Windows, Android, and iOS operating systems.
ï‚Ą Code editing, debugging, and code analysis are just
a few of the capabilities and tools that are included
in the IDE.
ï‚Ą It supports a variety of programming languages,
including Python, C++, C#, Visual Basic, and others.
ï‚Ą Features
Supports Python Coding in Visual studio
Available in both paid and free version
PyCharm
ï‚Ą The Jet Brains created PyCharm, a cross-platform
Integrated Development Environment (IDE)
created specifically for Python.
ï‚Ą It is the most popular IDE and is accessible in
both a premium and a free open-source version.
ï‚Ą Features
Smart code navigation
Errors Highlighting
Powerful debugger
Supports Python web development frameworks,
i.e., Angular JS, Javascript
Google Colab
ï‚Ą Google Colab is the short form for “Google Colabortory“. It is
an executable document that lets you write, run, and share
code or you can think as an improved version of “Jupyter
Notebook” stored in Google Drive.
ï‚Ą You might be wondering about the word “Notebook“, in simple
words it is just a document that includes executable lines of
code along
with text, images, figures, tables, graphs, equations, and
much more that even a layman can able to get insights about
the concepts behind it not just developers/programmers out
there.
ï‚Ą It is widely used by data scientists, analysts, and machine
learning enthusiasts due to its unique features and
advantages.
Google Colab Features
ï‚Ą Cloud-based notebook interface: Users can access
Colab from a web browser, eliminating the need for
complex installations or setting up local development
environments.
ï‚Ą Pre-installed Libraries: Certainly! Google Colab comes
with several pre-installed libraries and packages such as
NumPy, Pandas, Matplotlib, and much more that are
commonly used in data science, machine learning, and
deep learning tasks.
ï‚Ą Real-time CollaborationGoogle Drive: It offers a
collaborative environment for individuals and teams to
work on projects, data analysis, machine learning tasks,
and more.
Variables:
ï‚Ą Variables are nothing but reserved memory locations to
store values. This means that when you create a variable
you reserve some space in memory.
ï‚Ą It is the name use to declare any value either it can be int,
float, complex or any other type.
ï‚Ą It is created at the moment we assign a value and refers to
a memory location.
ï‚Ą String variable can be declared either by ‘ ’ or “ ”.
Eg: a=10
a=“name”
a=10.5
Rules for Variables:
ï‚Ą A variable can have a short name (like x and y) or a more
descriptive name (age, carname, total_volume , etc)
ï‚Ą A variable name must start with a letter or the underscore
character.
ï‚Ą A variable name cannot start with a number
ï‚Ą A variable name can only contain alpha-numeric characters
and underscores(A-Z,0-9 and _).
ï‚Ą Variables names are case-sensitive( age,Age and AGE are
three different variables).
Assigned values to
variables:
Python variables do not need explicit declaration to reserve memory space.
The declaration happens automatically when you assign a value to a
variable.
The equal sign (=) is used to assign values to variables.
eg: n=100
This is read or interpreted as “n is assigned the value 100”. N can be used
in a statement or expression and its value will be substituted.
Later, if you change the value of n and use it again, the new value will be
substituted instead
Python Identifiers:
ï‚Ą Identifier is a name used to identify a variable, function,
class or a module.
ï‚Ą It can start with letter A to Z (or) a to z, an underscore(_)
followed by zero or more letters, underscores and digits(0-9).
ï‚Ą It doesn’t allow special characters like @,$,% with
identifiers.
ï‚Ą These are case sensitive i.e., Manpower and manpower are
two different identifiers.
Examples:
Valid examples Invalid examples
Abc10d 99
ABC_DE 9abc
_abc X+Y
_ For
Reserved Keywords:
ï‚Ą These are the reserved words used in
Python.
ï‚Ą These names cannot be used as either
identifiers or constants or variables.
False Await Else Import pass
None Break Except In raise
True Class Finally Is return
And Continue For Lambda try
As Def From Nonlocal while
Assert Del Global Not with
Async Elif If Or yield
How to get list of keywords in
Python:
>>> import keyword
>>> print(keyword.kwlist)
Comments:
ï‚Ą it helps the beginners to understand any
tougher logics and also to recollect the logic
they have written.
ï‚Ą In c programming comments starts with /* and
ends with */.
ï‚Ą In python comments starts with #
Eg: # printing
# hello world
Eg: ””” it is also
an example of
multi line comments”””
Lines and Indentations:
ï‚Ą Most of the programming languages like c, c++, and java
use braces {} to define a block of code. Python uses
indentation
ï‚Ą Python doesn’t support braces to indicate block of codes for
class and function, definitions or flow control. Block of codes
are denoted by line indentation.
ï‚Ą All the continuous lines indented with same number of
spaces would form a block. Python strictly follows
indentation rules to indicate the blocks.
ï‚Ą Incorrect indentation will results indentation error.
Example:
if 5>2:
Print(“five is greater than two!”)
This gives an error as there is an indentation
missing.
if 5>2:
print(“five is greater than two!”)
Quotations:
ï‚Ą Python accepts single ('), double (") and triple
(''' or """) quotes to denote string literals, as
long as the same type of quote starts and ends
the string.
ï‚Ą The strings created by using single and double
quotes are the same. In other words, we can
use single and double quotes interchangeably
when we declare a string.
Expressions:
ï‚Ą An expression is a combination of values,
variables, and operators. An expression is
evaluated using assignment operator. Examples:
ï‚Ą Y=x + 17
ï‚Ą >>> x=10
ï‚Ą >>> z=x+20
ï‚Ą >>> z
ï‚Ą 30
ï‚Ą A value all by itself is a simple expression, and so
is a variable.
ï‚Ą >>> y=20
Statements:
ï‚Ą A statement is an instruction that the
Python interpreter can execute.
ï‚Ą We have normally two basic
statements, the assignment statement
and the print statement.
ï‚Ą Some other kinds of statements that
are if statements, while statements,
and for statements generally called as
control flows.
examples
ï‚Ą Examples: An assignment statement
creates new variables and gives them
values: >>> x=10
ï‚Ą An print statement is something which
is an input from the user, to be printed /
displayed on to the screen (or ) monitor.
ï‚Ą >>> print(“ICFAI ")
ï‚Ą ICFAi
Data types in Python:
ï‚Ą Variables can hold values, and every value
has a data-type.
ï‚Ą Python is a dynamically typed language
ï‚Ą Python provides us the type() function, which
returns the type of the variable passed.
ï‚Ą Type represents the kind of value and
determines how the value can be used.
Types of datatypes:
ï‚Ą There are 5 basic types of datatypes as
mentioned:
1. Numeric
2. Dictionary
3. Boolean
4. Set and
5. Sequence type
MUTABLE vs IMMUTABLE:
ï‚Ą Mutable: These are of type list , dict , set . Custom classes are
generally mutable.
list=[‘orange’, ‘pink’, ‘yellow’]
list[0]= ‘red’
list[-2]= ‘blue’
ï‚Ą Immutable: These are of in-built
types like int, float, bool, string,
unicode, tuple. In simple words
an immutable object can’t be changed
after it is created.
Eg: tuple1=(0,1,2,3)
tuple1[0]=4
Print(tuple1)
Fundamental Datatypes:
ï‚Ą These datatypes are created by numerical
values.
1. Integer
2. Floating number
3. Complex numbers
4. Boolean and
5. Strings
INTEGER:
ï‚Ą represented as <class ‘int’>.
ï‚Ą Consists of either positive or negative whole
numbers.
ï‚Ą Python2 version has int, long but python3 version
has only int.
ï‚Ą There is not length of the integer value unlike other
datatypes.
Eg: a=1234
b=(-4567)
c=0
d=(123456789123456789123456788+1)
FLOATING NUMBER:
ï‚Ą Represented as <class ‘float’>.
ï‚Ą Generally specified with a decimal point values.
ï‚Ą It also accepts a scientific notation like a character
e/E.
Eg: a=4.2
b=4. or .2
c= .4e7
d= 4.2e-4
COMPLEX NUMBERS:
ï‚Ą Represented as <class ‘complex’>.
ï‚Ą these are ordered pair i.e., a+bJ or a+bj.
ï‚Ą Where j is the imaginary number i.e., square root of -
1.
ï‚Ą Here the values are considered as a floating
numbers.
Eg: a=2-14j
b= 2.0+3j
BOOLEAN:
ï‚Ą Represented as <class ‘bool’>.
ï‚Ą It is the datatype with two built-in values, “True” or
“False”.
ï‚Ą Non-Boolean objects can also be evaluated in
Boolean context.
Eg: a=6;b=7
a>b
print(type(True))
print(type(False))
print(type(false))
STRINGS:
ï‚Ą Represented as <class ‘str’>.
ï‚Ą These are arrays of bytes representing Unicode
characters.
ï‚Ą These are the collection of characters in a ‘’,””,’’’.
ï‚Ą Here we don’t have any datatype like char in python.
1. How to create a string?
2. How to access the values of a string?
I C F A I T E C H s
Example:
1. How to create a string
string1=(“ICFAI TECH”)
print(“string with the use of double
quotes:”)
print(string1)
2. How to access elements :
string1=(“ICFAI TECH”)
print(string1[4])
print(string1[-7])
Number data types:
ï‚Ą We have 4 types in number datatypes:
1. Binary
2. Decimal
3. Octal and
4. Hexadecimal.
ï‚Ą Binary: it is a number system with base 2 and
computer can understand only binary numbers(0
and 1). Represented as 0b.
ï‚Ą Decimal: is most widely used with base 10.
Represented from 0 to 9.
ï‚Ą Octal: it is number system with base 8 and
represented as 0o.
ï‚Ą Hexadecimal: a number system with base 16 and
represented as 0x.
Inbuilt Functions:
ï‚Ą The Python built-in functions are
defined as the functions whose
functionality is pre-defined in Python.
ï‚Ą The python interpreter has several
functions that are always present for
use.
UNIT 1 PYTHON introduction and basic level
Function Description
abs() Returns the absolute value of a number
all() Returns True if all items in an iterable object are true
any() Returns True if any item in an iterable object is true
ascii()
Returns a readable version of an object. Replaces none-ascii
characters with escape character
bin() Returns the binary version of a number
bool() Returns the boolean value of the specified object
bytearray() Returns an array of bytes
bytes() Returns a bytes object
callable() Returns True if the specified object is callable, otherwise False
chr() Returns a character from the specified Unicode code.
compile()
Returns the specified source as an
object, ready to be executed
complex() Returns a complex number
delattr()
Deletes the specified attribute
(property or method) from the
specified object
dict() Returns a dictionary (Array)
dir()
Returns a list of the specified object's
properties and methods
divmod()
Returns the quotient and the
remainder when argument1 is
divided by argument2
enumerate(
)
Takes a collection (e.g. a tuple) and
returns it as an enumerate object
eval() Evaluates and executes an expression
exec()
Executes the specified code (or
object)
filter()
Use a filter function to exclude items
in an iterable object
float() Returns a floating point number
getattr()
Returns the value of the specified attribute (property or
method)
globals() Returns the current global symbol table as a dictionary
hasattr()
Returns True if the specified object has the specified attribute
(property/method)
hash() Returns the hash value of a specified object
help() Executes the built-in help system
hex() Converts a number into a hexadecimal value
id() Returns the id of an object
input() Allowing user input
int() Returns an integer number
isinstance()
Returns True if a specified object is an instance of a specified
object
issubclass()
Returns True if a specified class is a subclass of a specified
object
iter() Returns an iterator object
len() Returns the length of an object
list() Returns a list
locals()
Returns an updated dictionary of the current local
symbol table
map()
Returns the specified iterator with the specified
function applied to each item
max() Returns the largest item in an iterable
memoryview() Returns a memory view object
min() Returns the smallest item in an iterable
next() Returns the next item in an iterable
object() Returns a new object
oct() Converts a number into an octal
open() Opens a file and returns a file object
ord()
Convert an integer representing the Unicode of the
specified character
pow() Returns the value of x to the power of y
print() Prints to the standard output device
property() Gets, sets, deletes a property
range()
Returns a sequence of numbers, starting from 0 and
increments by 1 (by default)
repr() Returns a readable version of an object
reversed() Returns a reversed iterator
round() Rounds a numbers
set() Returns a new set object
setattr()
Sets an attribute (property/method) of an
object
slice() Returns a slice object
sorted() Returns a sorted list
@staticmethod() Converts a method into a static method
str() Returns a string object
sum() Sums the items of an iterator
super()
Returns an object that represents the parent
class
tuple() Returns a tuple
type() Returns the type of an object
vars() Returns the __dict__ property of an object
zip()
Returns an iterator, from two or more
iterators
Datatype conversions:
ï‚Ą There are two types of conversions:
1. Implicit: automatic conversion
eg: a=5
print(type(a))
2. Explicit: it requires user involvement.
This can be done with the help of int(),
str(), float() etc.,
EXPLICIT CONVERSIONS:
ï‚Ą Converting number to string: using str() function.
Eg: a=10
s=str(a)
print(s)
print(type(s))
ï‚Ą Converting string to number: using int(), float()
function.
Eg: s= ‘50’
n=int(s) f=float(s)
print(n) print(f)
print(type(n)) print(type(f))
Example:
ï‚Ą Converting floating point to integer: using int()
function.
Eg: f=10.0
n=int(f)
print(n)
print(type(n))
ï‚Ą Converting integer to float type: using float()
function.
Eg: n=10
f=float(n)
print(f)
print(type(f))
‱ Converting list to a tuple and tuple to a list:
using list(), tuple() function.
Eg: t=(1,3,2,4)
l=[5,6,7,8]
T=tuple(l) L=list(t)
print(T) print(L)
print(type(T)) print(type(L))
Python Operators:
ï‚Ą The operator can be defined as a symbol which is
responsible for a particular operation between two
operands
ï‚Ą Python provides a variety of operators.
1. Arithmetic Operators
2. Comparison Operators
3. Assignment Operators
4. Logical Operators
5. Bitwise Operators
6. Membership Operators and
7. Identity Operators.
Arithmetic Operators:
ï‚Ą Arithmetic operators are used to perform arithmetic
operations between two operands.
Comparison Operators:
ï‚Ą Comparison operators are used to
comparing the value of the two
operands and returns Boolean true or
false accordingly.
Assignment Operators:
ï‚Ą The assignment operators are used to assign the
value of the right expression to the left operand.
Logical Operators:
ï‚Ą The logical operators are used primarily
in the expression evaluation to make a
decision.
Bitwise Operators:
ï‚Ą The bitwise operators perform bit by bit operation on the values of the
two operands.
Membership Operators:
ï‚Ą Python membership operators are used to check the membership of
value inside a Python data structure.
ï‚Ą If the value is present in the data structure, then the resulting value is
true otherwise it returns false.
UNIT 1 PYTHON introduction and basic level
Identity Operators:
ï‚Ą The identity operators are used to
decide whether an element certain
class or type.
UNIT 1 PYTHON introduction and basic level
LIST
ï‚Ą A list in Python is used to store the sequence
of various types of data. Python lists are
mutable type its mean we can modify its
element after it created
ï‚Ą A list can be defined as a collection of values
or items of different types. The items in the
list are separated with the comma (,) and
enclosed with the square brackets [].
ï‚Ą L1 = ["John", 102, "USA"]
ï‚Ą L2 = [1, 2, 3, 4, 5, 6]
List characteristics
The list has the following
characteristics:
ï‚Ą The lists are ordered.
ï‚Ą The element of the list can access by
index.
ï‚Ą The lists are the mutable type.
ï‚Ą A list can store the number of various
elements.
List indexing and splitting
ï‚Ą The indexing is processed in the same way as it happens
with the strings.
ï‚Ą The elements of the list can be accessed by using the
slice operator [].
ï‚Ą The index starts from 0 and goes to length - 1.
ï‚Ą The first element of the list is stored at the 0th index, the
second element of the list is stored at the 1st index, and
so on
ï‚Ą list_variable (start: stop: step)
ï‚Ą The start denotes the starting index position of the list.
ï‚Ą The stop denotes the last index position of the list.
ï‚Ą The step is used to skip the nth element within a start :
stop
UNIT 1 PYTHON introduction and basic level
ï‚Ą Python provides the flexibility to use the negative
indexing also.
ï‚Ą The negative indices are counted from the right.
ï‚Ą The last element (rightmost) of the list has the index -1;
ï‚Ą its adjacent left element is present at the index -2 and so
on until the left-most elements are encountered.
Updating List values
ï‚Ą Lists are the most versatile data structures in Python
since they are mutable, and their values can be
updated by using the slice and assignment operator.
ï‚Ą Python also provides append() and insert() methods,
which can be used to add values to the list.
list = [1, 2, 3, 4, 5, 6]
print(list)
# It will assign value to the value to the second index
list[2] = 10
print(list)
# Adding multiple-element
list[1:3] = [89, 78]
print(list)
# It will add value at the end of the list
list[-1] = 25
print(list)
ï‚Ą The list elements can also be deleted
by using the del keyword.
ï‚Ą Python also provides us the remove()
method if we do not know which
element is to be deleted from the list.
list = [1, 2, 3, 4, 5, 6]
print(list)
# It will assign value to the value to the second in
dex
del list[3]
#it will delete the third element from the list
del keyword
Iterating a List
ï‚Ą A list can be iterated by using a for - in
loop. A simple list containing four
strings, which can be iterated as
follows.
List
=[“Rahim”,”Amy”,”Pradeep”,”Prashanthi”]
for i in list:
print(i)
Adding Elements to the List
ï‚Ą Python provides append() function which is used to add an
element to the list.
ï‚Ą However, the function can only add value to the end of the list.
#Declaring the empty list
l =[]
#Number of elements will be entered by the user
n = int(input("Enter the number of elements in the list:"))
# for loop to take the input
for i in range(0,n):
# The input is taken from the user and added to the list as the item
l.append(input("Enter the item:"))
print("printing the list items..")
# traversal loop to print the list items
for i in l:
print(i, end = " ")
Removing Elements from the List
ï‚Ą Python provides the remove() function
which is used to remove the element
from the list.
list = [0,1,2,3,4]
print("printing original list: ");
for i in list:
print(i,end=" ")
list.remove(2)
print("nprinting the list after the removal of first element...")
for i in list:
print(i,end=" ")
List Operations
ï‚Ą The concatenation (+) and repetition (*) operators work in
the same way as they were working with the strings.
ï‚Ą Consider a Lists l1 = [1, 2, 3, 4], and l2 = [5, 6, 7, 8] to perf
orm operation.
Operator Description Example
Repetition The repetition operator
enables the list elements
to be repeated multiple
times.
L1*2 = [1, 2, 3, 4, 1, 2, 3, 4]
Concatenation It concatenates the list
mentioned on either side
of the operator.
l1+l2 = [1, 2, 3, 4, 5, 6, 7, 8]
Membership It returns true if a
particular item exists in a
particular list otherwise
false.
print(2 in l1) prints True.
Iteration The for loop is used to
iterate over the list
for i in l1:
print(i)
List Built-in Functions and
Methods
ï‚Ą Python provides the following built-in
functions, which can be used with the
lists
SN Function Description Example
1 cmp(list1,
list2)
It compares the
elements of both the
lists.
This method is not used in the
Python 3 and the above versions.
2 len(list) It is used to calculate
the length of the list.
L1 = [1,2,3,4,5,6,7,8]
print(len(L1))
8
3 max(list) It returns the
maximum element
of the list.
L1 = [12,34,26,48,72]
print(max(L1))
72
4 min(list) It returns the
minimum element of
the list.
L1 = [12,34,26,48,72]
print(min(L1))
12
5 list(seq) It converts any
sequence to the list.
str = "Johnson"
s = list(str)
List methods:
ï‚Ą The list data type has some more methods.
Here are all of the methods of list objects:
ï‚Ą Del()
ï‚Ą Append()
ï‚Ą Extend()
ï‚Ą Insert()
ï‚Ą Pop()
ï‚Ą Remove()
ï‚Ą Reverse()
ï‚Ą Sort()
Delete & Append methods
ï‚Ą Delete: Delete a list or an item from a list
>>> x=[5,3,8,6]
>>> del(x[1]) #deletes the index position 1 in a list
>>> x
[5, 8, 6]
>>> del(x)
>>> x # complete list gets deleted
ï‚Ą Append: Append an item to a list
>>> x=[1,5,8,4]
>>> x.append(10)
>>> x
[1, 5, 8, 4, 10]
Extend & Insert methods
ï‚Ą Extend: Append a sequence to a list.
>>> x=[1,2,3,4]
>>> y=[3,6,9,1]
>>> x.extend(y)
>>> x
[1, 2, 3, 4, 3, 6, 9, 1]
ï‚Ą Insert: To add an item at the specified index, use the insert ()
method:
>>> x=[1,2,4,6,7]
>>> x.insert(2,10) #insert(index no, item to be inserted)
>>> x
[1, 2, 10, 4, 6, 7]
-------------------------
>>> x.insert(4,['a',11])
>>> x
[1, 2, 10, 4, ['a', 11], 6, 7]
Pop & Remove methods
ï‚Ą Pop: The pop() method removes the specified index, (or the last item if
index is not specified) or simply pops the last item of list and returns
the item.
>>> x=[1, 2, 10, 4, 6, 7]
>>> x.pop()
7
>>> x
[1, 2, 10, 4, 6]
-----------------------------------
>>> x=[1, 2, 10, 4, 6]
>>> x.pop(2)
10
>>> x
[1, 2, 4, 6]
ï‚Ą Remove: The remove() method removes the specified item from a
given list.
>>> x=[1,33,2,10,4,6]
>>> x.remove(33)
>>> x
[1, 2, 10, 4, 6]
>>> x.remove(4)
>>> x
[1, 2, 10, 6]
Reverse & Sort
ï‚Ą Reverse: Reverse the order of a given list.
>>> x=[1,2,3,4,5,6,7]
>>> x.reverse()
>>> x
[7, 6, 5, 4, 3, 2, 1]
ï‚Ą Sort: Sorts the elements in ascending order
>>> x=[7, 6, 5, 4, 3, 2, 1]
>>> x.sort()
>>> x
[1, 2, 3, 4, 5, 6, 7]
-----------------------
>>> x=[10,1,5,3,8,7]
>>> x.sort()
>>> x
[1, 3, 5, 7, 8, 10]
List slices:
EX:1 >>> list1=range(1,6)
>>> list1
range(1, 6)
>>> print(list1)
range(1, 6)
---------------------
EX:2 >>> list1=[1,2,3,4,5,6,7,8,9,10]
>>> list1[1:]
[2, 3, 4, 5, 6, 7, 8, 9, 10]
-------------------------------
Ex:3>>> list1[:1]
ï‚Ą [1]
----------------------------
ï‚Ą >>> list1[2:5]
ï‚Ą [3, 4, 5]
-----------------------------
ï‚Ą >>> list1[:6]
ï‚Ą [1, 2, 3, 4, 5, 6]
-----------------------------
ï‚Ą >>> list1[1:2:4]
ï‚Ą [2]
----------------------------------
ï‚Ą >>> list1[1:8:2]
ï‚Ą [2, 4, 6, 8]
List loop
ï‚Ą Loops are control structures used to repeat a given section of code a
certain number of times or until a particular condition is met.
Method #1: For loop
#list of items
list = [‘I',‘C',‘F',‘A',‘I']
i = 1
#Iterating over the list
for item in list:
print ('college ',i,' is ',item)
i = i+1
ï‚Ą Output:
college 1 is I
college 2 is C
college 3 is F
college 4 is A
college 5 is I
Method #2: For loop and
range()
ï‚Ą In case we want to use the traditional for loop which iterates from number
x to number y.
list = [1, 3, 5, 7, 9]
# getting length of list
length = len(list)
# Iterating the index
# same as 'for i in range(len(list))'
for i in range(length):
print(list[i])
ï‚Ą Output:
1
3
5
7
9
Method #3: using while loop
# Python3 code to iterate over a list
list = [1, 3, 5, 7, 9]
# Getting length of list
length = len(list)
i = 0
# Iterating using while loop
while i < length:
print(list[i])
i += 1
O/P:1
3
5
7
9
Tuple
ï‚Ą Python Tuple is used to store the sequence of
immutable Python objects.
ï‚Ą The tuple is similar to lists since the value of the
items stored in the list can be changed, whereas the
tuple is immutable, and the value of the items stored
in the tuple cannot be changed.
ï‚Ą A tuple can be written as the collection of comma-
separated (,) values enclosed with the small ()
brackets.
ï‚Ą T1 = (101, "Peter", 22)
ï‚Ą T2 = ("Apple", "Banana", "Orange")
construct tuple in many
ways
ï‚Ą We can construct tuple in many ways:
ï‚Ą X=() #no item tuple
ï‚Ą X=(1,2,3)
ï‚Ą X=tuple(list1)
ï‚Ą X=1,2,3,4
TUPLE INDEXING AND SPLITTING
ï‚Ą The indexing and slicing in the tuple are similar to lists.
The indexing in the tuple starts from 0 and goes to
length(tuple) – 1
ï‚Ą The items in the tuple can be accessed by using the
index [] operator.
ï‚Ą Python also allows us to use the colon operator to
access multiple items in the tuple.
TUPLE OPERATIONS
ï‚Ą The operators like concatenation (+), repetition (*),
Membership (in) works in the same way as they work
with the list.
ï‚Ą Let's say Tuple t = (1, 2, 3, 4, 5) and Tuple t1 = (6, 7, 8,
9) are declared.
Operator Description Example
Repetition The repetition operator enables the
tuple elements to be repeated
multiple times.
T1*2 = (1, 2, 3, 4, 5, 1, 2,
3, 4, 5)
Concatenation It concatenates the tuple mentioned
on either side of the operator.
T1+T2 = (1, 2, 3, 4, 5, 6, 7,
8, 9)
Membership It returns true if a particular item
exists in the tuple otherwise false
print (2 in T1) prints True.
Iteration The for loop is used to iterate over
the tuple elements.
for i in T1:
print(i)
Output
1 2 3 4 5
TUPLE INBUILT FUNCTIONS
SN Function Description
1 cmp(tuple1, tuple2) It compares two tuples and
returns true if tuple1 is greater
than tuple2 otherwise false.
2 len(tuple) It calculates the length of the
tuple.
3 max(tuple) It returns the maximum
element of the tuple
4 min(tuple) It returns the minimum
element of the tuple.
5 tuple(seq) It converts the specified
sequence to the tuple.
Tuple Assignment
ï‚Ą Python has tuple assignment feature which enables you to assign more
than one variable at a time. In here, we have assigned tuple 1 with the
college information like college name, year, etc. and another tuple 2 with
the values in it like number (1, 2, 3
 7).
ï‚Ą For Example,
Here is the code,
>>> tup1 = (‘ICFAI', 'eng college','2024','cse', ‘AIML',‘AIDS');
>>> tup2 = (1,2,3,4,5,6,7);
>>> print(tup1[0])
ICFAI
>>> print(tup2[1:4])
(2, 3, 4)
Tuple 1 includes list of information of ICFAI
Tuple 2 includes list of numbers in it We call the value for [0] in tuple and for
tuple 2 we call the value between 1 and 4
ï‚Ą Run the above code- It gives name ICFAI for first tuple while for second
tuple it gives number (2, 3, 4)
Tuple as return values:
ï‚Ą A Tuple is a comma separated sequence of items. It is created with or
without (). Tuples are immutable.
ï‚Ą # A Python program to return multiple values from a method using tuple
ï‚Ą # This function returns a tuple
def fun():
str = “Icfai Tech"
x = 20
return str, x; # Return tuple, we could also
ï‚Ą # write (str, x)
ï‚Ą # Driver code to test above method
str, x = fun() # Assign returned tuple
print(str)
print(x)
ï‚Ą Output:
ICFAI Tech
20
Python Tuple Methods
Method Description
count() Returns the number of times a specified value occurs in a tuple
index() Searches the tuple for a specified value and returns the position of
where it was found
ython has two built-in methods that you can use on tuples.
Python has two built-in methods that you can use on tuples.
Syntax:
tuple.count(element)
Where the element is the element that is to be counted.
Syntax:
tuple.index(element, start, end)
Parameters:
‱element: The element to be searched.
‱start (Optional): The starting index from where the searching is
started
‱end (Optional): The ending index till where the searching is done
Using the Tuple count()
method
# Creating tuples
Tuple1 = (0, 1, 2, 3, 2, 3, 1, 3, 2)
Tuple2 = ('python', 'geek', 'python',
'for', 'java', 'python')
# count the appearance of 3
res = Tuple1.count(3)
print('Count of 3 in Tuple1 is:', res)
# count the appearance of python
res = Tuple2.count('python')
print('Count of Python in Tuple2 is:', res)
Count of 3 in Tuple1 is: 3 Count of Python in Tuple2 is: 3
Count of 3 in Tuple1 is: 3 Count of Python in Tuple2 is: 3
Using Tuple Index() Method
# Creating tuples
Tuple = (0, 1, 2, 3, 2, 3, 1, 3, 2)
# getting the index of 3
res = Tuple.index(3)
print('First occurrence of 3 is', res)
# getting the index of 3 after 4th
# index
res = Tuple.index(3, 4)
print('First occurrence of 3 after 4th index is:', res)
First occurrence of 3 is 3 First occurrence of 3 after 4th index is: 5
Set
ï‚Ą Strings ,List, & Tuples are built-in sequence collections.
ï‚Ą Dictionaries and sets are non-sequence collections
ï‚Ą Sets are unordered collection of unique values.
ï‚Ą Sets may contain only immutable objects,like strings, ints,
floats, and tuples that contain only elements
s={'red',1,'green','b',10.5}
ï‚Ą Setsare iterable,they not sequence and do not support
indexing and slicing with [] square brackets.
Print(s)
{1, 'b', 'green', 'red', 10.5}
Print(s[1])
TypeError: 'set' object is not subscriptable
ï‚Ą Duplicate stings was ignored(without
error)
ï‚Ą Sets are mutable,but set elemets must
be immutable. Therefore set cannot
have other sets as elements.
s={'red',1,'green','b',10.5,1,'red',10.5}
Print(s)
{1, 'b', 'green', 'red', 10.5}
SET
ï‚Ą A Python set is the collection of the
unordered items.
ï‚Ą Each element in the set must be unique,
immutable, and the sets remove the
duplicate elements.
ï‚Ą Sets are mutable which means we can modify
it after its creation.
ï‚Ą Sets are written with curly brackets.
ï‚Ą thisset = {"apple", "banana", "cherry"}
CREATING A SET
ï‚Ą The set can be created by enclosing the comma-
separated immutable items with the curly braces {}.
ï‚Ą Python also provides the set() method, which can be
used to create the set by the passed sequence
ï‚Ą It can contain any type of element such as integer,
float, tuple etc. But mutable elements (list,
dictionary, set) can't be a member of set.
1. s1={10,20,30,(5,6,7),40}
s1
{(5, 6, 7), 20, 40, 10, 30}
2. s1={10,20,30,[5,6,7],40}
Traceback (most recent call last):
File "<pyshell#5>", line 1, in <module>
s1={10,20,30,[5,6,7],40}
TypeError: unhashable type: 'list‘
3. s1={10,20,30,{5,6,7},40}
SET OPERATIONS
ï‚Ą Set can be performed mathematical operation such
as union, intersection, difference, and symmetric
difference.
ï‚Ą Python provides the facility to carry out these
operations with operators or methods
ADDING ITEMS TO THE SET
ï‚Ą Python provides the add() method and
update() method which can be used to add
some particular item to the set.
ï‚Ą The add() method is used to add a single
element whereas the update() method is used
to add multiple elements to the set.
Months = set(["January","February", "March", "April", "May", "June"])
print("nprinting the original set ... ")
print(months)
print("nAdding other months to the set...");
Months.add("July");
Months.add ("August");
print("nPrinting the modified set...");
print(Months)
print("nlooping through the set elements ... ")
for i in Months:
print(i)
REMOVING ITEMS FROM THE SET
ï‚Ą Python provides the discard() method and remove() method
which can be used to remove the items from the set.
ï‚Ą The difference between these function, using discard() function if
the item does not exist in the set then the set remain unchanged
whereas remove() method will through an error.
months = set(["January","February", "March", "April", "May", "June"])
print("nprinting the original set ... ")
print(months)
print("nRemoving some months from the set...");
months.discard("January");
months.discard("May");
print("nPrinting the modified set...");
print(months)
print("nlooping through the set elements ... ")
for i in months:
print(i)
DIFFERENCE BETWEEN DISCARD() AND
REMOVE()
ï‚Ą Despite the fact that discard() and remove() method both perform the
same task, There is one main difference between discard() and remove().
ï‚Ą If the key to be deleted from the set using discard() doesn't exist in the
set, the Python will not give the error. The program maintains its control
flow.
ï‚Ą On the other hand, if the item to be deleted from the set using remove()
doesn't exist in the set, the Python will raise an error.
Months = set(["January","February", "March", "April", "May", "June"])
print("nprinting the original set ... ")
print(Months)
print("nRemoving items through discard() method...");
Months.discard("Feb"); #will not give an error although the keyfeb is not available in the set
print("nprinting the modified set...")
print(Months)
print("nRemoving items through remove() method...");
Months.remove("Jan") #will give an error as the key jan is not
available in the set.
print("nPrinting the modified set...")
print(Months)
UNION OF TWO SETS
ï‚Ą The union of two sets is calculated by using the pipe
(|) operator.
ï‚Ą The union of the two sets contains all the items that
are present in both the sets.
ï‚Ą Python also provides the union() method which can
also be used to calculate the union of two sets.
Days1 = {"Monday","Tuesday","Wednesday","Thursday", "Sunday"}
Days2 = {"Friday","Saturday","Sunday"}
print(Days1|Days2) #printing the union of the sets
{'Saturday', 'Sunday', 'Friday', 'Thursday', 'Wednesday',
'Tuesday', 'Monday'}
INTERSECTION OF TWO SETS
ï‚Ą The intersection of two sets can be performed by the and & operator
or the intersection() function. The intersection of the two sets is given
as the set of the elements that common in both sets.
ï‚Ą The intersection_update() method removes the items from the
original set that are not present in both the sets (all the sets if more
than one are specified).
ï‚Ą The intersection_update() method is different from the intersection()
method since it modifies the original set by removing the unwanted
items, on the other hand, the intersection() method returns a new set.
Days1 = {"Monday","Tuesday", "Wednesday", "Thursday"}
Days2 = {"Monday","Tuesday","Sunday", "Friday"}
print(Days1&Days2) #prints the intersection of the two sets
{'Sunday'}
DIFFERENCE OF TWO SETS
ï‚Ą The difference of two sets can be calculated by using
the subtraction (-) operator or intersection() method.
ï‚Ą Suppose there are two sets A and B, and the
difference is A-B that denotes the resulting set will be
obtained that element of A, which is not present in
the set B.
Days1 = {"Monday", "Tuesday", "Wednesday", "Thursday"}
Days2 = {"Monday", "Tuesday", "Sunday"}
print(Days1-Days2) #{"Wednesday", "Thursday" will be printed}
SET COMPARISONS
ï‚Ą Python allows us to use the comparison
operators i.e., <, >, <=, >= , == with the sets by
using which we can check whether a set is a
subset, superset, or equivalent to other set. The
boolean true or false is returned depending
upon the items present inside the sets.
Days1 = {"Monday", "Tuesday", "Wednesday", "Thursday"}
Days2 = {"Monday", "Tuesday"}
Days3 = {"Monday", "Tuesday", "Friday"}
#Days1 is the superset of Days2 hence it will print true.
print (Days1>Days2)
#prints false since Days1 is not the subset of Days2
print (Days1<Days2)
Python Set Methods
ï‚Ą Python has a set of built-in methods that you can use on sets.
Method Description
add() Adds an element to the set
clear() Removes all the elements from the set
copy() Returns a copy of the set
difference() Returns a set containing the difference between two or more sets
difference_update() Removes the items in this set that are also included in another, specified set
discard() Remove the specified item
intersection() Returns a set, that is the intersection of two or more sets
intersection_update() Removes the items in this set that are not present in other, specified set(s)
isdisjoint() Returns whether two sets have a intersection or not
issubset() Returns whether another set contains this set or not
issuperset() Returns whether this set contains another set or not
pop() Removes an element from the set
remove() Removes the specified element
symmetric_difference() Returns a set with the symmetric differences of two sets
symmetric_difference_upda
te()
inserts the symmetric differences from this set and another
union() Return a set containing the union of sets
update() Update the set with another set, or any other iterable
FROZEN SET DATA
STRUCTURE
ï‚Ą The frozen sets are the immutable form of the normal sets, i.e., the items of the
frozen set cannot be changed and therefore it can be used as a key in the
dictionary.
ï‚Ą The elements of the frozen set cannot be changed after the creation. We cannot
change or append the content of the frozen sets by using the methods like
add() or remove().
ï‚Ą The frozenset() method is used to create the frozenset object. The iterable
sequence is passed into this method which is converted into the frozen set as a
return type of the method.
Frozenset = frozenset([1,2,3,4,5])
print(type(Frozenset))
print("nprinting the content of frozen set...")
for i in Frozenset:
print(i);
Frozenset.add(6) #gives an error since we cannot change the content of Frozense
t after creation
DICTIONARY DATA STRUCTURE
ï‚Ą Dictionaries are used to store data
values in key:value pairs.
ï‚Ą A dictionary is a collection which is
ordered*, changeable and do not allow
duplicates.
ï‚Ą As of Python version 3.7, dictionaries
are ordered. In Python 3.6 and earlier,
dictionaries are unordered.
ï‚Ą Dictionaries are written with curly
brackets, and have keys and values:
Duplicates Not Allowed
ï‚Ą Dictionaries cannot have two items with
the same key:
ï‚Ą thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964,
"year": 2020
}
print(thisdict)
The dict() Constructor
ï‚Ą It is also possible to use
the dict() constructor to m
ï‚Ą thisdict = dict(name = "John", age = 36,
country = "Norway")
print(thisdict)ake a dictionary.
Python - Access Dictionary Items
1. thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
x = thisdict["model"]
2. x = thisdict.get("model")
3. x = thisdict.keys()
4. x = thisdict.values()
5. x = thisdict.items()
6. car["color"] = "red"
There is also a method called get() that will give you the same result:
Change Dictionary Items
1. thisdict["year"] = 2018
2. thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
thisdict.update({"year": 2020})
Remove Dictionary Items
1. thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
thisdict.pop("model")
print(thisdict)
2. thisdict.popitem() #remove last element
#before 3.7 version random element deleted
3. del thisdict["model"]
4. thisdict.clear()
INTRODUCTION
ï‚Ą Python Dictionary is used to store the data in a key-
value pair format.
ï‚Ą The dictionary is the data type in Python, which can
simulate the real-life data arrangement where some
specific value exists for some particular key.
ï‚Ą It is the mutable data-structure.
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
CREATING THE DICTIONARY
ï‚Ą The dictionary can be created by using multiple key-
value pairs enclosed with the curly brackets {}, and
each key is separated from its value by the colon (:)
ï‚Ą Python provides the built-in function dict() method
which is also used to create dictionary.
ï‚Ą The empty curly braces {} is used to create empty
dictionary
Dict = {"Name": "Tom", "Age": 22}
ACCESSING THE DICTIONARY
VALUES
ï‚Ą The values can be accessed in the
dictionary by using the keys as keys
are unique in the dictionary.
Employee = {"Name": "John", "Age": 29, "salary":25000,"Company":"GOOGLE"}
print(type(Employee))
print("printing Employee data .... ")
print("Name : %s" %Employee["Name"])
print("Age : %d" %Employee["Age"])
print("Salary : %d" %Employee["salary"])
print("Company : %s" %Employee["Company"])
UPDATING DICTIONARY VALUES
ï‚Ą The dictionary is a
mutable data type, and
its values can be
updated by using the
specific keys.
ï‚Ą The value can be
updated along with key
Dict[key] = value.
ï‚Ą The update() method is
also used to update an
existing value.
# Creating an empty Dictionary
Dict = {}
print("Empty Dictionary: ")
print(Dict)
# Adding elements to dictionary one at a time
Dict[0] = 'Peter'
Dict[2] = 'Joseph'
Dict[3] = 'Ricky'
print("nDictionary after adding 3 elements: ")
print(Dict)
# Adding set of values
# with a single Key
# The Emp_ages doesn't exist to dictionary
Dict['Emp_ages'] = 20, 33, 24
print("nDictionary after adding 3 elements: ")
print(Dict)
# Updating existing Key's Value
Dict[3] = 'JavaTpoint'
print("nUpdated key value: ")
print(Dict)
Python Dictionary Methods
Method Description
clear() Removes all the elements from the dictionary
copy() Returns a copy of the dictionary
fromkeys() Returns a dictionary with the specified keys and value
get() Returns the value of the specified key
items() Returns a list containing a tuple for each key value pair
keys() Returns a list containing the dictionary's keys
pop() Removes the element with the specified key
popitem() Removes the last inserted key-value pair
setdefault(
)
Returns the value of the specified key. If the key does not exist: insert the key,
with the specified value
update() Updates the dictionary with the specified key-value pairs
values() Returns a list of all the values in the dictionary
DELETING ELEMENTS USING DEL
KEYWORD
ï‚Ą The items of the dictionary can be
deleted by using the del keyword.
Employee = {"Name": "John", "Age": 29, "salary":
25000,"Company":"GOOGLE"}
print(type(Employee))
print("printing Employee data .... ")
print(Employee)
print("Deleting some of the employee data")
del Employee["Name"]
del Employee["Company"]
ITERATING DICTIONARY
ï‚Ą A dictionary can be iterated using for
loop
Employee = {"Name": "John", "Age": 29, "salary":25000,"Company"
:"GOOGLE"}
for x in Employee:
print(x)
PROPERTIES OF DICTIONARY
KEYS
ï‚Ą 1. In the dictionary, we cannot store multiple values
for the same keys. If we pass more than one value
for a single key, then the value which is last assigned
is considered as the value of the key.
ï‚Ą 2. In python, the key cannot be any mutable object.
We can use numbers, strings, or tuples as the key,
but we cannot use any mutable object like the list as
the key in the dictionary.
BUILT-IN DICTIONARY
FUNCTIONS
SN Function Description
1 cmp(dict1,
dict2)
It compares the items of both the dictionary and returns
true if the first dictionary values are greater than the
second dictionary, otherwise it returns false.
2 len(dict) It is used to calculate the length of the dictionary.
3 str(dict) It converts the dictionary into the printable string
representation.
4 type(variabl
e)
It is used to print the type of the passed variable.
BUILT-IN DICTIONARY METHODS
SN Method Description
1 dict.clear() It is used to delete all the items of the
dictionary.
2 dict.copy() It returns a shallow copy of the dictionary.
3 dict.fromkeys(iterable
, value = None, /)
Create a new dictionary from the iterable with
the values equal to value.
4 dict.get(key, default = "None") It is used to get the value specified for the
passed key.
5 dict.has_key(key) It returns true if the dictionary contains the
specified key.
6 dict.items() It returns all the key-value pairs as a tuple.
7 dict.keys() It returns all the keys of the dictionary.
8 dict.setdefault(key,default= "No
ne")
It is used to set the key to the default value if
the key is not specified in the dictionary
9 dict.update(dict2) It updates the dictionary by adding the key-
value pair of dict2 to this dictionary.
10 dict.values() It returns all the values of the dictionary.
THANK YOU

More Related Content

PPTX
Python_Introduction_Good_PPT.pptx
PPTX
Python final presentation kirti ppt1
PPTX
Chapter 2: Basics of programming pyton programming
PPT
python-ppt.ppt
PPT
python-ppt.ppt
PPTX
Chapter - 1.pptx
PDF
REPORT ON AUDIT COURSE PYTHON BY SANA 2.pdf
PDF
Python unit1
Python_Introduction_Good_PPT.pptx
Python final presentation kirti ppt1
Chapter 2: Basics of programming pyton programming
python-ppt.ppt
python-ppt.ppt
Chapter - 1.pptx
REPORT ON AUDIT COURSE PYTHON BY SANA 2.pdf
Python unit1

Similar to UNIT 1 PYTHON introduction and basic level (20)

PPT
1-ppt-python.ppt
PPTX
Python Mastery: A Comprehensive Guide to Setting Up Your Development Environment
PPTX
Session-1_Introduction to Python.pptx
PDF
session5-Getting stated with Python.pdf
PPTX
Python Programming-1.pptx of python by computer
PPT
Python for students step by step guidance
PPTX
Python PPT by Sushil Sir.pptx
PDF
Class_X_PYTHON_J.pdf
PPTX
Lecture1.pptx
PDF
Python Programing Bio computing,basic concepts lab,,
PDF
Py-Slides- easuajsjsjejejjwlqpqpqpp1.pdf
PPT
notwa dfdfvs gf fdgfgh s thgfgh frg reggg
PPT
program on python what is python where it was started by whom started
PPT
Python Over View (Python for mobile app Devt)1.ppt
PPT
Py-Slides-1.ppt1234444444444444444444444444444444444444444
PPT
Python slides for the beginners to learn
PPT
Py-Slides-1.pptPy-Slides-1.pptPy-Slides-1.pptPy-Slides-1.ppt
PPTX
MODULE 1.pptx
PPTX
a9855c3532e13484ee6a39ba30218896d7c0d863-1676987272842.pptx
PDF
Python Programming Part 1.pdf
1-ppt-python.ppt
Python Mastery: A Comprehensive Guide to Setting Up Your Development Environment
Session-1_Introduction to Python.pptx
session5-Getting stated with Python.pdf
Python Programming-1.pptx of python by computer
Python for students step by step guidance
Python PPT by Sushil Sir.pptx
Class_X_PYTHON_J.pdf
Lecture1.pptx
Python Programing Bio computing,basic concepts lab,,
Py-Slides- easuajsjsjejejjwlqpqpqpp1.pdf
notwa dfdfvs gf fdgfgh s thgfgh frg reggg
program on python what is python where it was started by whom started
Python Over View (Python for mobile app Devt)1.ppt
Py-Slides-1.ppt1234444444444444444444444444444444444444444
Python slides for the beginners to learn
Py-Slides-1.pptPy-Slides-1.pptPy-Slides-1.pptPy-Slides-1.ppt
MODULE 1.pptx
a9855c3532e13484ee6a39ba30218896d7c0d863-1676987272842.pptx
Python Programming Part 1.pdf
Ad

Recently uploaded (20)

PPTX
Essential Infomation Tech presentation.pptx
PDF
Wondershare Filmora 15 Crack With Activation Key [2025
PPTX
Reimagine Home Health with the Power of Agentic AI​
PDF
How to Migrate SBCGlobal Email to Yahoo Easily
PPTX
Oracle E-Business Suite: A Comprehensive Guide for Modern Enterprises
PPTX
L1 - Introduction to python Backend.pptx
PDF
Design an Analysis of Algorithms II-SECS-1021-03
PPTX
Agentic AI Use Case- Contract Lifecycle Management (CLM).pptx
PPTX
Lecture 3: Operating Systems Introduction to Computer Hardware Systems
 
PDF
Softaken Excel to vCard Converter Software.pdf
PPTX
ai tools demonstartion for schools and inter college
PDF
AI in Product Development-omnex systems
PDF
Understanding Forklifts - TECH EHS Solution
PDF
PTS Company Brochure 2025 (1).pdf.......
PDF
medical staffing services at VALiNTRY
PDF
T3DD25 TYPO3 Content Blocks - Deep Dive by André Kraus
PDF
Audit Checklist Design Aligning with ISO, IATF, and Industry Standards — Omne...
PDF
top salesforce developer skills in 2025.pdf
PDF
Digital Strategies for Manufacturing Companies
PDF
Which alternative to Crystal Reports is best for small or large businesses.pdf
Essential Infomation Tech presentation.pptx
Wondershare Filmora 15 Crack With Activation Key [2025
Reimagine Home Health with the Power of Agentic AI​
How to Migrate SBCGlobal Email to Yahoo Easily
Oracle E-Business Suite: A Comprehensive Guide for Modern Enterprises
L1 - Introduction to python Backend.pptx
Design an Analysis of Algorithms II-SECS-1021-03
Agentic AI Use Case- Contract Lifecycle Management (CLM).pptx
Lecture 3: Operating Systems Introduction to Computer Hardware Systems
 
Softaken Excel to vCard Converter Software.pdf
ai tools demonstartion for schools and inter college
AI in Product Development-omnex systems
Understanding Forklifts - TECH EHS Solution
PTS Company Brochure 2025 (1).pdf.......
medical staffing services at VALiNTRY
T3DD25 TYPO3 Content Blocks - Deep Dive by André Kraus
Audit Checklist Design Aligning with ISO, IATF, and Industry Standards — Omne...
top salesforce developer skills in 2025.pdf
Digital Strategies for Manufacturing Companies
Which alternative to Crystal Reports is best for small or large businesses.pdf
Ad

UNIT 1 PYTHON introduction and basic level

  • 2. Contents Of UNIT-I ï‚Ą Introduction ï‚Ą History of Python Programming ï‚Ą Features ï‚Ą Applications ï‚Ą Versions ,Flavors in Python ï‚Ą Programming Modes ï‚Ą Download & Install the Python in Windows & Linux ï‚Ą How to set Python Environment in the System? ï‚Ą Downloading and Installing Anaconda, Jupyter Notebook & Spyder ï‚Ą Python IDE - Jupyter Notebook Environment, Spyder Environment
  • 3. Introduction ï‚Ą Python is a general purpose high level programming language ï‚Ą Interactive ï‚Ą Interpreted ï‚Ą Object Oriented & Scripting Language
  • 4. History of Python Centrum Wiskunde & Informatica (CWI) is the National Research Institute for Mathematics and Computer Science in the Netherlands. 20th Guido van Rossum
  • 5. Where it is derived from? ï‚Ą Python is named after the BBC TV comedy show Monty Python’s Flying Circus. It is not named after the Python snake.
  • 6. Python is derived from ï‚Ą Functional Programming features from C ï‚Ą OOPs features from C++ ï‚Ą Scripting language features from Perl and Shell Script ï‚Ą Modular Programming features from Moudula-3
  • 8. Applications ï‚Ą Data Science ï‚Ą Artificial Intelligence ï‚Ą Machine Learning ï‚Ą Deep Learning ï‚Ą Data Analysis ï‚Ą NLP ï‚Ą Neural Networks ï‚Ą IOT ï‚Ą Robotics
  • 9. Existing Vs Python Comparing Python to Other Languages ï‚Ą Python code is typically 3-5 times shorter than equivalent JAVA code ï‚Ą It is often 5-10 times shorter than equivalent C++ code ï‚Ą And even shorter than C code
  • 11. Programming Modes ï‚Ą How to execute python program: ï‚Ą By using Python Interpreter, we can execute python programs in 2 modes .they are: 1. Immediate mode 2. Script mode ï‚Ą 1. Immediate mode: (in windows)  In the mode, you type Python expressions into the Python Interpreter window, and the interpreter immediately shows the results.
  • 12. 2. Script mode (in windows) ï‚Ą we can open IDLE python then click on file, open new file and we can write python program and save as filename.py. After that ,to run this program press F5 button or click run button click Run module.
  • 13. Python Versions: The implementation of Python was started in December 1989. In February 1991, Guido Van Rossum published the code (labeled version 0.9.0) to alt.sources. ï‚ȘPython 1.0 - January 1994 Python 1.0 was released with new features like lambda, map, filter, and reduce.  Python 1.5 - December 31, 1997  Python 1.6 - September 5, 2000 ï‚ȘPython 2.0 - October 16, 2000 Python 2.0 added new features such as list comprehensions, garbage collection systems.  Python 2.1 - April 17, 2001  Python 2.2 - December 21, 2001  Python 2.3 - July 29, 2003  Python 2.4 - November 30, 2004  Python 2.5 - September 19, 2006  Python 2.6 - October 1, 2008  Python 2.7 - July 3, 2010 Python 2.7 is latest version of python2
  • 14. ï‚Ș Python 3.0 - On December 3, 2008, Python 3.0 (also called "Py3K") was released. It was designed to rectify the fundamental flaw of the language.  Python 3.1 - June 27, 2009  Python 3.2 - February 20, 2011  Python 3.3 - September 29, 2012  Python 3.4 - March 16, 2014  Python 3.5 - September 13, 2015  Python 3.7.0 - June 27, 2018  Python 3.7.1 - October 13, 2018  Python 3.7.2 - December 24, 2015  Python 3.7.3 - March 25, 2019  Python 3.7.4 - July 8, 2019 Python 3 is not backward compatible with Python 2.
  • 15. Flavors of Python ï‚Ą Types of Python compilers are referred as flavors of Python. 1. CPython: ï‚Ą 2. JPython: ï‚Ą 3. IronPython: ï‚Ą 4. PyPy:
  • 16. Contd
 ï‚Ą 5. Ruby Python: ï‚Ą 6. Pythonxy: ï‚Ą 7.Anaconda Python: ï‚Ą 8. Stackless Python:
  • 17. Download & Install the Python in Windows https://www.python.org/downloads/
  • 18. Installing Python in Windows ï‚Ą After downloading Run python-3.8.5. exe file. Install it and click next. ï‚Ą In window search button, type IDLE python, we get version of python installed python interpreter:
  • 19. Installing Python in ubuntu 1. Open terminal via Ctrl+Alt+T or searching for “Terminal” from app launcher. 2. Ubuntu 16.04 comes with both Python 2 and Python 3 by default.
  • 20. 3. If it is not there, install Python use following command : sudo apt-get install python 3.8 4. To check updates use following command sudo apt-get update
  • 21. 5. To know the versions of the python type following command:
  • 22. Python Environment Setup in the System Interactive Mode and Scripting Mode of Programming
  • 23. How to install Anaconda software in windows https://www.anaconda.com/distribution/ Anaconda is not an IDE, Anaconda is a Python distribution, (including for commercial use and redistribution). It includes more than 400 of the most popular Python packages for science, math, engineering, and data analysis.
  • 26. Python IDE - Jupyter Notebook Environment
  • 28. Python IDE - Spyder Environment
  • 30. Microsoft Visual Studio ï‚Ą An integrated development environment (IDE) called Microsoft Visual Studio is used to create software for the Windows, Android, and iOS operating systems. ï‚Ą Code editing, debugging, and code analysis are just a few of the capabilities and tools that are included in the IDE. ï‚Ą It supports a variety of programming languages, including Python, C++, C#, Visual Basic, and others. ï‚Ą Features Supports Python Coding in Visual studio Available in both paid and free version
  • 31. PyCharm ï‚Ą The Jet Brains created PyCharm, a cross-platform Integrated Development Environment (IDE) created specifically for Python. ï‚Ą It is the most popular IDE and is accessible in both a premium and a free open-source version. ï‚Ą Features Smart code navigation Errors Highlighting Powerful debugger Supports Python web development frameworks, i.e., Angular JS, Javascript
  • 32. Google Colab ï‚Ą Google Colab is the short form for “Google Colabortory“. It is an executable document that lets you write, run, and share code or you can think as an improved version of “Jupyter Notebook” stored in Google Drive. ï‚Ą You might be wondering about the word “Notebook“, in simple words it is just a document that includes executable lines of code along with text, images, figures, tables, graphs, equations, and much more that even a layman can able to get insights about the concepts behind it not just developers/programmers out there. ï‚Ą It is widely used by data scientists, analysts, and machine learning enthusiasts due to its unique features and advantages.
  • 33. Google Colab Features ï‚Ą Cloud-based notebook interface: Users can access Colab from a web browser, eliminating the need for complex installations or setting up local development environments. ï‚Ą Pre-installed Libraries: Certainly! Google Colab comes with several pre-installed libraries and packages such as NumPy, Pandas, Matplotlib, and much more that are commonly used in data science, machine learning, and deep learning tasks. ï‚Ą Real-time CollaborationGoogle Drive: It offers a collaborative environment for individuals and teams to work on projects, data analysis, machine learning tasks, and more.
  • 34. Variables: ï‚Ą Variables are nothing but reserved memory locations to store values. This means that when you create a variable you reserve some space in memory. ï‚Ą It is the name use to declare any value either it can be int, float, complex or any other type. ï‚Ą It is created at the moment we assign a value and refers to a memory location. ï‚Ą String variable can be declared either by ‘ ’ or “ ”. Eg: a=10 a=“name” a=10.5
  • 35. Rules for Variables: ï‚Ą A variable can have a short name (like x and y) or a more descriptive name (age, carname, total_volume , etc) ï‚Ą A variable name must start with a letter or the underscore character. ï‚Ą A variable name cannot start with a number ï‚Ą A variable name can only contain alpha-numeric characters and underscores(A-Z,0-9 and _). ï‚Ą Variables names are case-sensitive( age,Age and AGE are three different variables).
  • 36. Assigned values to variables: Python variables do not need explicit declaration to reserve memory space. The declaration happens automatically when you assign a value to a variable. The equal sign (=) is used to assign values to variables. eg: n=100 This is read or interpreted as “n is assigned the value 100”. N can be used in a statement or expression and its value will be substituted. Later, if you change the value of n and use it again, the new value will be substituted instead
  • 37. Python Identifiers: ï‚Ą Identifier is a name used to identify a variable, function, class or a module. ï‚Ą It can start with letter A to Z (or) a to z, an underscore(_) followed by zero or more letters, underscores and digits(0-9). ï‚Ą It doesn’t allow special characters like @,$,% with identifiers. ï‚Ą These are case sensitive i.e., Manpower and manpower are two different identifiers.
  • 38. Examples: Valid examples Invalid examples Abc10d 99 ABC_DE 9abc _abc X+Y _ For
  • 39. Reserved Keywords: ï‚Ą These are the reserved words used in Python. ï‚Ą These names cannot be used as either identifiers or constants or variables. False Await Else Import pass None Break Except In raise True Class Finally Is return And Continue For Lambda try As Def From Nonlocal while Assert Del Global Not with Async Elif If Or yield
  • 40. How to get list of keywords in Python: >>> import keyword >>> print(keyword.kwlist)
  • 41. Comments: ï‚Ą it helps the beginners to understand any tougher logics and also to recollect the logic they have written. ï‚Ą In c programming comments starts with /* and ends with */. ï‚Ą In python comments starts with # Eg: # printing # hello world Eg: ””” it is also an example of multi line comments”””
  • 42. Lines and Indentations: ï‚Ą Most of the programming languages like c, c++, and java use braces {} to define a block of code. Python uses indentation ï‚Ą Python doesn’t support braces to indicate block of codes for class and function, definitions or flow control. Block of codes are denoted by line indentation. ï‚Ą All the continuous lines indented with same number of spaces would form a block. Python strictly follows indentation rules to indicate the blocks. ï‚Ą Incorrect indentation will results indentation error.
  • 43. Example: if 5>2: Print(“five is greater than two!”) This gives an error as there is an indentation missing. if 5>2: print(“five is greater than two!”)
  • 44. Quotations: ï‚Ą Python accepts single ('), double (") and triple (''' or """) quotes to denote string literals, as long as the same type of quote starts and ends the string. ï‚Ą The strings created by using single and double quotes are the same. In other words, we can use single and double quotes interchangeably when we declare a string.
  • 45. Expressions: ï‚Ą An expression is a combination of values, variables, and operators. An expression is evaluated using assignment operator. Examples: ï‚Ą Y=x + 17 ï‚Ą >>> x=10 ï‚Ą >>> z=x+20 ï‚Ą >>> z ï‚Ą 30 ï‚Ą A value all by itself is a simple expression, and so is a variable. ï‚Ą >>> y=20
  • 46. Statements: ï‚Ą A statement is an instruction that the Python interpreter can execute. ï‚Ą We have normally two basic statements, the assignment statement and the print statement. ï‚Ą Some other kinds of statements that are if statements, while statements, and for statements generally called as control flows.
  • 47. examples ï‚Ą Examples: An assignment statement creates new variables and gives them values: >>> x=10 ï‚Ą An print statement is something which is an input from the user, to be printed / displayed on to the screen (or ) monitor. ï‚Ą >>> print(“ICFAI ") ï‚Ą ICFAi
  • 48. Data types in Python: ï‚Ą Variables can hold values, and every value has a data-type. ï‚Ą Python is a dynamically typed language ï‚Ą Python provides us the type() function, which returns the type of the variable passed. ï‚Ą Type represents the kind of value and determines how the value can be used.
  • 49. Types of datatypes: ï‚Ą There are 5 basic types of datatypes as mentioned: 1. Numeric 2. Dictionary 3. Boolean 4. Set and 5. Sequence type
  • 50. MUTABLE vs IMMUTABLE: ï‚Ą Mutable: These are of type list , dict , set . Custom classes are generally mutable. list=[‘orange’, ‘pink’, ‘yellow’] list[0]= ‘red’ list[-2]= ‘blue’ ï‚Ą Immutable: These are of in-built types like int, float, bool, string, unicode, tuple. In simple words an immutable object can’t be changed after it is created. Eg: tuple1=(0,1,2,3) tuple1[0]=4 Print(tuple1)
  • 51. Fundamental Datatypes: ï‚Ą These datatypes are created by numerical values. 1. Integer 2. Floating number 3. Complex numbers 4. Boolean and 5. Strings
  • 52. INTEGER: ï‚Ą represented as <class ‘int’>. ï‚Ą Consists of either positive or negative whole numbers. ï‚Ą Python2 version has int, long but python3 version has only int. ï‚Ą There is not length of the integer value unlike other datatypes. Eg: a=1234 b=(-4567) c=0 d=(123456789123456789123456788+1)
  • 53. FLOATING NUMBER: ï‚Ą Represented as <class ‘float’>. ï‚Ą Generally specified with a decimal point values. ï‚Ą It also accepts a scientific notation like a character e/E. Eg: a=4.2 b=4. or .2 c= .4e7 d= 4.2e-4
  • 54. COMPLEX NUMBERS: ï‚Ą Represented as <class ‘complex’>. ï‚Ą these are ordered pair i.e., a+bJ or a+bj. ï‚Ą Where j is the imaginary number i.e., square root of - 1. ï‚Ą Here the values are considered as a floating numbers. Eg: a=2-14j b= 2.0+3j
  • 55. BOOLEAN: ï‚Ą Represented as <class ‘bool’>. ï‚Ą It is the datatype with two built-in values, “True” or “False”. ï‚Ą Non-Boolean objects can also be evaluated in Boolean context. Eg: a=6;b=7 a>b print(type(True)) print(type(False)) print(type(false))
  • 56. STRINGS: ï‚Ą Represented as <class ‘str’>. ï‚Ą These are arrays of bytes representing Unicode characters. ï‚Ą These are the collection of characters in a ‘’,””,’’’. ï‚Ą Here we don’t have any datatype like char in python. 1. How to create a string? 2. How to access the values of a string? I C F A I T E C H s
  • 57. Example: 1. How to create a string string1=(“ICFAI TECH”) print(“string with the use of double quotes:”) print(string1) 2. How to access elements : string1=(“ICFAI TECH”) print(string1[4]) print(string1[-7])
  • 58. Number data types: ï‚Ą We have 4 types in number datatypes: 1. Binary 2. Decimal 3. Octal and 4. Hexadecimal.
  • 59. ï‚Ą Binary: it is a number system with base 2 and computer can understand only binary numbers(0 and 1). Represented as 0b. ï‚Ą Decimal: is most widely used with base 10. Represented from 0 to 9. ï‚Ą Octal: it is number system with base 8 and represented as 0o. ï‚Ą Hexadecimal: a number system with base 16 and represented as 0x.
  • 60. Inbuilt Functions: ï‚Ą The Python built-in functions are defined as the functions whose functionality is pre-defined in Python. ï‚Ą The python interpreter has several functions that are always present for use.
  • 62. Function Description abs() Returns the absolute value of a number all() Returns True if all items in an iterable object are true any() Returns True if any item in an iterable object is true ascii() Returns a readable version of an object. Replaces none-ascii characters with escape character bin() Returns the binary version of a number bool() Returns the boolean value of the specified object bytearray() Returns an array of bytes bytes() Returns a bytes object callable() Returns True if the specified object is callable, otherwise False chr() Returns a character from the specified Unicode code.
  • 63. compile() Returns the specified source as an object, ready to be executed complex() Returns a complex number delattr() Deletes the specified attribute (property or method) from the specified object dict() Returns a dictionary (Array) dir() Returns a list of the specified object's properties and methods divmod() Returns the quotient and the remainder when argument1 is divided by argument2 enumerate( ) Takes a collection (e.g. a tuple) and returns it as an enumerate object eval() Evaluates and executes an expression exec() Executes the specified code (or object) filter() Use a filter function to exclude items in an iterable object float() Returns a floating point number
  • 64. getattr() Returns the value of the specified attribute (property or method) globals() Returns the current global symbol table as a dictionary hasattr() Returns True if the specified object has the specified attribute (property/method) hash() Returns the hash value of a specified object help() Executes the built-in help system hex() Converts a number into a hexadecimal value id() Returns the id of an object input() Allowing user input int() Returns an integer number isinstance() Returns True if a specified object is an instance of a specified object issubclass() Returns True if a specified class is a subclass of a specified object iter() Returns an iterator object len() Returns the length of an object list() Returns a list
  • 65. locals() Returns an updated dictionary of the current local symbol table map() Returns the specified iterator with the specified function applied to each item max() Returns the largest item in an iterable memoryview() Returns a memory view object min() Returns the smallest item in an iterable next() Returns the next item in an iterable object() Returns a new object oct() Converts a number into an octal open() Opens a file and returns a file object ord() Convert an integer representing the Unicode of the specified character pow() Returns the value of x to the power of y print() Prints to the standard output device property() Gets, sets, deletes a property range() Returns a sequence of numbers, starting from 0 and increments by 1 (by default)
  • 66. repr() Returns a readable version of an object reversed() Returns a reversed iterator round() Rounds a numbers set() Returns a new set object setattr() Sets an attribute (property/method) of an object slice() Returns a slice object sorted() Returns a sorted list @staticmethod() Converts a method into a static method str() Returns a string object sum() Sums the items of an iterator super() Returns an object that represents the parent class tuple() Returns a tuple type() Returns the type of an object vars() Returns the __dict__ property of an object zip() Returns an iterator, from two or more iterators
  • 67. Datatype conversions: ï‚Ą There are two types of conversions: 1. Implicit: automatic conversion eg: a=5 print(type(a)) 2. Explicit: it requires user involvement. This can be done with the help of int(), str(), float() etc.,
  • 68. EXPLICIT CONVERSIONS: ï‚Ą Converting number to string: using str() function. Eg: a=10 s=str(a) print(s) print(type(s)) ï‚Ą Converting string to number: using int(), float() function. Eg: s= ‘50’ n=int(s) f=float(s) print(n) print(f) print(type(n)) print(type(f))
  • 69. Example: ï‚Ą Converting floating point to integer: using int() function. Eg: f=10.0 n=int(f) print(n) print(type(n)) ï‚Ą Converting integer to float type: using float() function. Eg: n=10 f=float(n) print(f) print(type(f))
  • 70. ‱ Converting list to a tuple and tuple to a list: using list(), tuple() function. Eg: t=(1,3,2,4) l=[5,6,7,8] T=tuple(l) L=list(t) print(T) print(L) print(type(T)) print(type(L))
  • 71. Python Operators: ï‚Ą The operator can be defined as a symbol which is responsible for a particular operation between two operands ï‚Ą Python provides a variety of operators. 1. Arithmetic Operators 2. Comparison Operators 3. Assignment Operators 4. Logical Operators 5. Bitwise Operators 6. Membership Operators and 7. Identity Operators.
  • 72. Arithmetic Operators: ï‚Ą Arithmetic operators are used to perform arithmetic operations between two operands.
  • 73. Comparison Operators: ï‚Ą Comparison operators are used to comparing the value of the two operands and returns Boolean true or false accordingly.
  • 74. Assignment Operators: ï‚Ą The assignment operators are used to assign the value of the right expression to the left operand.
  • 75. Logical Operators: ï‚Ą The logical operators are used primarily in the expression evaluation to make a decision.
  • 76. Bitwise Operators: ï‚Ą The bitwise operators perform bit by bit operation on the values of the two operands.
  • 77. Membership Operators: ï‚Ą Python membership operators are used to check the membership of value inside a Python data structure. ï‚Ą If the value is present in the data structure, then the resulting value is true otherwise it returns false.
  • 79. Identity Operators: ï‚Ą The identity operators are used to decide whether an element certain class or type.
  • 81. LIST ï‚Ą A list in Python is used to store the sequence of various types of data. Python lists are mutable type its mean we can modify its element after it created ï‚Ą A list can be defined as a collection of values or items of different types. The items in the list are separated with the comma (,) and enclosed with the square brackets []. ï‚Ą L1 = ["John", 102, "USA"] ï‚Ą L2 = [1, 2, 3, 4, 5, 6]
  • 82. List characteristics The list has the following characteristics: ï‚Ą The lists are ordered. ï‚Ą The element of the list can access by index. ï‚Ą The lists are the mutable type. ï‚Ą A list can store the number of various elements.
  • 83. List indexing and splitting ï‚Ą The indexing is processed in the same way as it happens with the strings. ï‚Ą The elements of the list can be accessed by using the slice operator []. ï‚Ą The index starts from 0 and goes to length - 1. ï‚Ą The first element of the list is stored at the 0th index, the second element of the list is stored at the 1st index, and so on ï‚Ą list_variable (start: stop: step) ï‚Ą The start denotes the starting index position of the list. ï‚Ą The stop denotes the last index position of the list. ï‚Ą The step is used to skip the nth element within a start : stop
  • 85. ï‚Ą Python provides the flexibility to use the negative indexing also. ï‚Ą The negative indices are counted from the right. ï‚Ą The last element (rightmost) of the list has the index -1; ï‚Ą its adjacent left element is present at the index -2 and so on until the left-most elements are encountered.
  • 86. Updating List values ï‚Ą Lists are the most versatile data structures in Python since they are mutable, and their values can be updated by using the slice and assignment operator. ï‚Ą Python also provides append() and insert() methods, which can be used to add values to the list. list = [1, 2, 3, 4, 5, 6] print(list) # It will assign value to the value to the second index list[2] = 10 print(list) # Adding multiple-element list[1:3] = [89, 78] print(list) # It will add value at the end of the list list[-1] = 25 print(list)
  • 87. ï‚Ą The list elements can also be deleted by using the del keyword. ï‚Ą Python also provides us the remove() method if we do not know which element is to be deleted from the list. list = [1, 2, 3, 4, 5, 6] print(list) # It will assign value to the value to the second in dex del list[3] #it will delete the third element from the list del keyword
  • 88. Iterating a List ï‚Ą A list can be iterated by using a for - in loop. A simple list containing four strings, which can be iterated as follows. List =[“Rahim”,”Amy”,”Pradeep”,”Prashanthi”] for i in list: print(i)
  • 89. Adding Elements to the List ï‚Ą Python provides append() function which is used to add an element to the list. ï‚Ą However, the function can only add value to the end of the list. #Declaring the empty list l =[] #Number of elements will be entered by the user n = int(input("Enter the number of elements in the list:")) # for loop to take the input for i in range(0,n): # The input is taken from the user and added to the list as the item l.append(input("Enter the item:")) print("printing the list items..") # traversal loop to print the list items for i in l: print(i, end = " ")
  • 90. Removing Elements from the List ï‚Ą Python provides the remove() function which is used to remove the element from the list. list = [0,1,2,3,4] print("printing original list: "); for i in list: print(i,end=" ") list.remove(2) print("nprinting the list after the removal of first element...") for i in list: print(i,end=" ")
  • 91. List Operations ï‚Ą The concatenation (+) and repetition (*) operators work in the same way as they were working with the strings. ï‚Ą Consider a Lists l1 = [1, 2, 3, 4], and l2 = [5, 6, 7, 8] to perf orm operation. Operator Description Example Repetition The repetition operator enables the list elements to be repeated multiple times. L1*2 = [1, 2, 3, 4, 1, 2, 3, 4] Concatenation It concatenates the list mentioned on either side of the operator. l1+l2 = [1, 2, 3, 4, 5, 6, 7, 8] Membership It returns true if a particular item exists in a particular list otherwise false. print(2 in l1) prints True. Iteration The for loop is used to iterate over the list for i in l1: print(i)
  • 92. List Built-in Functions and Methods ï‚Ą Python provides the following built-in functions, which can be used with the lists SN Function Description Example 1 cmp(list1, list2) It compares the elements of both the lists. This method is not used in the Python 3 and the above versions. 2 len(list) It is used to calculate the length of the list. L1 = [1,2,3,4,5,6,7,8] print(len(L1)) 8 3 max(list) It returns the maximum element of the list. L1 = [12,34,26,48,72] print(max(L1)) 72 4 min(list) It returns the minimum element of the list. L1 = [12,34,26,48,72] print(min(L1)) 12 5 list(seq) It converts any sequence to the list. str = "Johnson" s = list(str)
  • 93. List methods: ï‚Ą The list data type has some more methods. Here are all of the methods of list objects: ï‚Ą Del() ï‚Ą Append() ï‚Ą Extend() ï‚Ą Insert() ï‚Ą Pop() ï‚Ą Remove() ï‚Ą Reverse() ï‚Ą Sort()
  • 94. Delete & Append methods ï‚Ą Delete: Delete a list or an item from a list >>> x=[5,3,8,6] >>> del(x[1]) #deletes the index position 1 in a list >>> x [5, 8, 6] >>> del(x) >>> x # complete list gets deleted ï‚Ą Append: Append an item to a list >>> x=[1,5,8,4] >>> x.append(10) >>> x [1, 5, 8, 4, 10]
  • 95. Extend & Insert methods ï‚Ą Extend: Append a sequence to a list. >>> x=[1,2,3,4] >>> y=[3,6,9,1] >>> x.extend(y) >>> x [1, 2, 3, 4, 3, 6, 9, 1] ï‚Ą Insert: To add an item at the specified index, use the insert () method: >>> x=[1,2,4,6,7] >>> x.insert(2,10) #insert(index no, item to be inserted) >>> x [1, 2, 10, 4, 6, 7] ------------------------- >>> x.insert(4,['a',11]) >>> x [1, 2, 10, 4, ['a', 11], 6, 7]
  • 96. Pop & Remove methods ï‚Ą Pop: The pop() method removes the specified index, (or the last item if index is not specified) or simply pops the last item of list and returns the item. >>> x=[1, 2, 10, 4, 6, 7] >>> x.pop() 7 >>> x [1, 2, 10, 4, 6] ----------------------------------- >>> x=[1, 2, 10, 4, 6] >>> x.pop(2) 10 >>> x [1, 2, 4, 6] ï‚Ą Remove: The remove() method removes the specified item from a given list. >>> x=[1,33,2,10,4,6] >>> x.remove(33) >>> x [1, 2, 10, 4, 6] >>> x.remove(4) >>> x [1, 2, 10, 6]
  • 97. Reverse & Sort ï‚Ą Reverse: Reverse the order of a given list. >>> x=[1,2,3,4,5,6,7] >>> x.reverse() >>> x [7, 6, 5, 4, 3, 2, 1] ï‚Ą Sort: Sorts the elements in ascending order >>> x=[7, 6, 5, 4, 3, 2, 1] >>> x.sort() >>> x [1, 2, 3, 4, 5, 6, 7] ----------------------- >>> x=[10,1,5,3,8,7] >>> x.sort() >>> x [1, 3, 5, 7, 8, 10]
  • 98. List slices: EX:1 >>> list1=range(1,6) >>> list1 range(1, 6) >>> print(list1) range(1, 6) --------------------- EX:2 >>> list1=[1,2,3,4,5,6,7,8,9,10] >>> list1[1:] [2, 3, 4, 5, 6, 7, 8, 9, 10] ------------------------------- Ex:3>>> list1[:1] ï‚Ą [1] ---------------------------- ï‚Ą >>> list1[2:5] ï‚Ą [3, 4, 5] ----------------------------- ï‚Ą >>> list1[:6] ï‚Ą [1, 2, 3, 4, 5, 6] ----------------------------- ï‚Ą >>> list1[1:2:4] ï‚Ą [2] ---------------------------------- ï‚Ą >>> list1[1:8:2] ï‚Ą [2, 4, 6, 8]
  • 99. List loop ï‚Ą Loops are control structures used to repeat a given section of code a certain number of times or until a particular condition is met. Method #1: For loop #list of items list = [‘I',‘C',‘F',‘A',‘I'] i = 1 #Iterating over the list for item in list: print ('college ',i,' is ',item) i = i+1 ï‚Ą Output: college 1 is I college 2 is C college 3 is F college 4 is A college 5 is I
  • 100. Method #2: For loop and range() ï‚Ą In case we want to use the traditional for loop which iterates from number x to number y. list = [1, 3, 5, 7, 9] # getting length of list length = len(list) # Iterating the index # same as 'for i in range(len(list))' for i in range(length): print(list[i]) ï‚Ą Output: 1 3 5 7 9
  • 101. Method #3: using while loop # Python3 code to iterate over a list list = [1, 3, 5, 7, 9] # Getting length of list length = len(list) i = 0 # Iterating using while loop while i < length: print(list[i]) i += 1 O/P:1 3 5 7 9
  • 102. Tuple ï‚Ą Python Tuple is used to store the sequence of immutable Python objects. ï‚Ą The tuple is similar to lists since the value of the items stored in the list can be changed, whereas the tuple is immutable, and the value of the items stored in the tuple cannot be changed. ï‚Ą A tuple can be written as the collection of comma- separated (,) values enclosed with the small () brackets. ï‚Ą T1 = (101, "Peter", 22) ï‚Ą T2 = ("Apple", "Banana", "Orange")
  • 103. construct tuple in many ways ï‚Ą We can construct tuple in many ways: ï‚Ą X=() #no item tuple ï‚Ą X=(1,2,3) ï‚Ą X=tuple(list1) ï‚Ą X=1,2,3,4
  • 104. TUPLE INDEXING AND SPLITTING ï‚Ą The indexing and slicing in the tuple are similar to lists. The indexing in the tuple starts from 0 and goes to length(tuple) – 1 ï‚Ą The items in the tuple can be accessed by using the index [] operator. ï‚Ą Python also allows us to use the colon operator to access multiple items in the tuple.
  • 105. TUPLE OPERATIONS ï‚Ą The operators like concatenation (+), repetition (*), Membership (in) works in the same way as they work with the list. ï‚Ą Let's say Tuple t = (1, 2, 3, 4, 5) and Tuple t1 = (6, 7, 8, 9) are declared. Operator Description Example Repetition The repetition operator enables the tuple elements to be repeated multiple times. T1*2 = (1, 2, 3, 4, 5, 1, 2, 3, 4, 5) Concatenation It concatenates the tuple mentioned on either side of the operator. T1+T2 = (1, 2, 3, 4, 5, 6, 7, 8, 9) Membership It returns true if a particular item exists in the tuple otherwise false print (2 in T1) prints True. Iteration The for loop is used to iterate over the tuple elements. for i in T1: print(i) Output 1 2 3 4 5
  • 106. TUPLE INBUILT FUNCTIONS SN Function Description 1 cmp(tuple1, tuple2) It compares two tuples and returns true if tuple1 is greater than tuple2 otherwise false. 2 len(tuple) It calculates the length of the tuple. 3 max(tuple) It returns the maximum element of the tuple 4 min(tuple) It returns the minimum element of the tuple. 5 tuple(seq) It converts the specified sequence to the tuple.
  • 107. Tuple Assignment ï‚Ą Python has tuple assignment feature which enables you to assign more than one variable at a time. In here, we have assigned tuple 1 with the college information like college name, year, etc. and another tuple 2 with the values in it like number (1, 2, 3
 7). ï‚Ą For Example, Here is the code, >>> tup1 = (‘ICFAI', 'eng college','2024','cse', ‘AIML',‘AIDS'); >>> tup2 = (1,2,3,4,5,6,7); >>> print(tup1[0]) ICFAI >>> print(tup2[1:4]) (2, 3, 4) Tuple 1 includes list of information of ICFAI Tuple 2 includes list of numbers in it We call the value for [0] in tuple and for tuple 2 we call the value between 1 and 4 ï‚Ą Run the above code- It gives name ICFAI for first tuple while for second tuple it gives number (2, 3, 4)
  • 108. Tuple as return values: ï‚Ą A Tuple is a comma separated sequence of items. It is created with or without (). Tuples are immutable. ï‚Ą # A Python program to return multiple values from a method using tuple ï‚Ą # This function returns a tuple def fun(): str = “Icfai Tech" x = 20 return str, x; # Return tuple, we could also ï‚Ą # write (str, x) ï‚Ą # Driver code to test above method str, x = fun() # Assign returned tuple print(str) print(x) ï‚Ą Output: ICFAI Tech 20
  • 109. Python Tuple Methods Method Description count() Returns the number of times a specified value occurs in a tuple index() Searches the tuple for a specified value and returns the position of where it was found ython has two built-in methods that you can use on tuples. Python has two built-in methods that you can use on tuples. Syntax: tuple.count(element) Where the element is the element that is to be counted. Syntax: tuple.index(element, start, end) Parameters: ‱element: The element to be searched. ‱start (Optional): The starting index from where the searching is started ‱end (Optional): The ending index till where the searching is done
  • 110. Using the Tuple count() method # Creating tuples Tuple1 = (0, 1, 2, 3, 2, 3, 1, 3, 2) Tuple2 = ('python', 'geek', 'python', 'for', 'java', 'python') # count the appearance of 3 res = Tuple1.count(3) print('Count of 3 in Tuple1 is:', res) # count the appearance of python res = Tuple2.count('python') print('Count of Python in Tuple2 is:', res) Count of 3 in Tuple1 is: 3 Count of Python in Tuple2 is: 3 Count of 3 in Tuple1 is: 3 Count of Python in Tuple2 is: 3
  • 111. Using Tuple Index() Method # Creating tuples Tuple = (0, 1, 2, 3, 2, 3, 1, 3, 2) # getting the index of 3 res = Tuple.index(3) print('First occurrence of 3 is', res) # getting the index of 3 after 4th # index res = Tuple.index(3, 4) print('First occurrence of 3 after 4th index is:', res) First occurrence of 3 is 3 First occurrence of 3 after 4th index is: 5
  • 112. Set ï‚Ą Strings ,List, & Tuples are built-in sequence collections. ï‚Ą Dictionaries and sets are non-sequence collections ï‚Ą Sets are unordered collection of unique values. ï‚Ą Sets may contain only immutable objects,like strings, ints, floats, and tuples that contain only elements s={'red',1,'green','b',10.5} ï‚Ą Setsare iterable,they not sequence and do not support indexing and slicing with [] square brackets. Print(s) {1, 'b', 'green', 'red', 10.5} Print(s[1]) TypeError: 'set' object is not subscriptable
  • 113. ï‚Ą Duplicate stings was ignored(without error) ï‚Ą Sets are mutable,but set elemets must be immutable. Therefore set cannot have other sets as elements. s={'red',1,'green','b',10.5,1,'red',10.5} Print(s) {1, 'b', 'green', 'red', 10.5}
  • 114. SET ï‚Ą A Python set is the collection of the unordered items. ï‚Ą Each element in the set must be unique, immutable, and the sets remove the duplicate elements. ï‚Ą Sets are mutable which means we can modify it after its creation. ï‚Ą Sets are written with curly brackets. ï‚Ą thisset = {"apple", "banana", "cherry"}
  • 115. CREATING A SET ï‚Ą The set can be created by enclosing the comma- separated immutable items with the curly braces {}. ï‚Ą Python also provides the set() method, which can be used to create the set by the passed sequence ï‚Ą It can contain any type of element such as integer, float, tuple etc. But mutable elements (list, dictionary, set) can't be a member of set. 1. s1={10,20,30,(5,6,7),40} s1 {(5, 6, 7), 20, 40, 10, 30} 2. s1={10,20,30,[5,6,7],40} Traceback (most recent call last): File "<pyshell#5>", line 1, in <module> s1={10,20,30,[5,6,7],40} TypeError: unhashable type: 'list‘ 3. s1={10,20,30,{5,6,7},40}
  • 116. SET OPERATIONS ï‚Ą Set can be performed mathematical operation such as union, intersection, difference, and symmetric difference. ï‚Ą Python provides the facility to carry out these operations with operators or methods
  • 117. ADDING ITEMS TO THE SET ï‚Ą Python provides the add() method and update() method which can be used to add some particular item to the set. ï‚Ą The add() method is used to add a single element whereas the update() method is used to add multiple elements to the set. Months = set(["January","February", "March", "April", "May", "June"]) print("nprinting the original set ... ") print(months) print("nAdding other months to the set..."); Months.add("July"); Months.add ("August"); print("nPrinting the modified set..."); print(Months) print("nlooping through the set elements ... ") for i in Months: print(i)
  • 118. REMOVING ITEMS FROM THE SET ï‚Ą Python provides the discard() method and remove() method which can be used to remove the items from the set. ï‚Ą The difference between these function, using discard() function if the item does not exist in the set then the set remain unchanged whereas remove() method will through an error. months = set(["January","February", "March", "April", "May", "June"]) print("nprinting the original set ... ") print(months) print("nRemoving some months from the set..."); months.discard("January"); months.discard("May"); print("nPrinting the modified set..."); print(months) print("nlooping through the set elements ... ") for i in months: print(i)
  • 119. DIFFERENCE BETWEEN DISCARD() AND REMOVE() ï‚Ą Despite the fact that discard() and remove() method both perform the same task, There is one main difference between discard() and remove(). ï‚Ą If the key to be deleted from the set using discard() doesn't exist in the set, the Python will not give the error. The program maintains its control flow. ï‚Ą On the other hand, if the item to be deleted from the set using remove() doesn't exist in the set, the Python will raise an error. Months = set(["January","February", "March", "April", "May", "June"]) print("nprinting the original set ... ") print(Months) print("nRemoving items through discard() method..."); Months.discard("Feb"); #will not give an error although the keyfeb is not available in the set print("nprinting the modified set...") print(Months) print("nRemoving items through remove() method..."); Months.remove("Jan") #will give an error as the key jan is not available in the set. print("nPrinting the modified set...") print(Months)
  • 120. UNION OF TWO SETS ï‚Ą The union of two sets is calculated by using the pipe (|) operator. ï‚Ą The union of the two sets contains all the items that are present in both the sets. ï‚Ą Python also provides the union() method which can also be used to calculate the union of two sets. Days1 = {"Monday","Tuesday","Wednesday","Thursday", "Sunday"} Days2 = {"Friday","Saturday","Sunday"} print(Days1|Days2) #printing the union of the sets {'Saturday', 'Sunday', 'Friday', 'Thursday', 'Wednesday', 'Tuesday', 'Monday'}
  • 121. INTERSECTION OF TWO SETS ï‚Ą The intersection of two sets can be performed by the and & operator or the intersection() function. The intersection of the two sets is given as the set of the elements that common in both sets. ï‚Ą The intersection_update() method removes the items from the original set that are not present in both the sets (all the sets if more than one are specified). ï‚Ą The intersection_update() method is different from the intersection() method since it modifies the original set by removing the unwanted items, on the other hand, the intersection() method returns a new set. Days1 = {"Monday","Tuesday", "Wednesday", "Thursday"} Days2 = {"Monday","Tuesday","Sunday", "Friday"} print(Days1&Days2) #prints the intersection of the two sets {'Sunday'}
  • 122. DIFFERENCE OF TWO SETS ï‚Ą The difference of two sets can be calculated by using the subtraction (-) operator or intersection() method. ï‚Ą Suppose there are two sets A and B, and the difference is A-B that denotes the resulting set will be obtained that element of A, which is not present in the set B. Days1 = {"Monday", "Tuesday", "Wednesday", "Thursday"} Days2 = {"Monday", "Tuesday", "Sunday"} print(Days1-Days2) #{"Wednesday", "Thursday" will be printed}
  • 123. SET COMPARISONS ï‚Ą Python allows us to use the comparison operators i.e., <, >, <=, >= , == with the sets by using which we can check whether a set is a subset, superset, or equivalent to other set. The boolean true or false is returned depending upon the items present inside the sets. Days1 = {"Monday", "Tuesday", "Wednesday", "Thursday"} Days2 = {"Monday", "Tuesday"} Days3 = {"Monday", "Tuesday", "Friday"} #Days1 is the superset of Days2 hence it will print true. print (Days1>Days2) #prints false since Days1 is not the subset of Days2 print (Days1<Days2)
  • 124. Python Set Methods ï‚Ą Python has a set of built-in methods that you can use on sets. Method Description add() Adds an element to the set clear() Removes all the elements from the set copy() Returns a copy of the set difference() Returns a set containing the difference between two or more sets difference_update() Removes the items in this set that are also included in another, specified set discard() Remove the specified item intersection() Returns a set, that is the intersection of two or more sets intersection_update() Removes the items in this set that are not present in other, specified set(s) isdisjoint() Returns whether two sets have a intersection or not issubset() Returns whether another set contains this set or not issuperset() Returns whether this set contains another set or not pop() Removes an element from the set remove() Removes the specified element symmetric_difference() Returns a set with the symmetric differences of two sets symmetric_difference_upda te() inserts the symmetric differences from this set and another union() Return a set containing the union of sets update() Update the set with another set, or any other iterable
  • 125. FROZEN SET DATA STRUCTURE ï‚Ą The frozen sets are the immutable form of the normal sets, i.e., the items of the frozen set cannot be changed and therefore it can be used as a key in the dictionary. ï‚Ą The elements of the frozen set cannot be changed after the creation. We cannot change or append the content of the frozen sets by using the methods like add() or remove(). ï‚Ą The frozenset() method is used to create the frozenset object. The iterable sequence is passed into this method which is converted into the frozen set as a return type of the method. Frozenset = frozenset([1,2,3,4,5]) print(type(Frozenset)) print("nprinting the content of frozen set...") for i in Frozenset: print(i); Frozenset.add(6) #gives an error since we cannot change the content of Frozense t after creation
  • 127. ï‚Ą Dictionaries are used to store data values in key:value pairs. ï‚Ą A dictionary is a collection which is ordered*, changeable and do not allow duplicates. ï‚Ą As of Python version 3.7, dictionaries are ordered. In Python 3.6 and earlier, dictionaries are unordered. ï‚Ą Dictionaries are written with curly brackets, and have keys and values:
  • 128. Duplicates Not Allowed ï‚Ą Dictionaries cannot have two items with the same key: ï‚Ą thisdict = { "brand": "Ford", "model": "Mustang", "year": 1964, "year": 2020 } print(thisdict)
  • 129. The dict() Constructor ï‚Ą It is also possible to use the dict() constructor to m ï‚Ą thisdict = dict(name = "John", age = 36, country = "Norway") print(thisdict)ake a dictionary.
  • 130. Python - Access Dictionary Items 1. thisdict = { "brand": "Ford", "model": "Mustang", "year": 1964 } x = thisdict["model"] 2. x = thisdict.get("model") 3. x = thisdict.keys() 4. x = thisdict.values() 5. x = thisdict.items() 6. car["color"] = "red" There is also a method called get() that will give you the same result:
  • 131. Change Dictionary Items 1. thisdict["year"] = 2018 2. thisdict = { "brand": "Ford", "model": "Mustang", "year": 1964 } thisdict.update({"year": 2020})
  • 132. Remove Dictionary Items 1. thisdict = { "brand": "Ford", "model": "Mustang", "year": 1964 } thisdict.pop("model") print(thisdict) 2. thisdict.popitem() #remove last element #before 3.7 version random element deleted 3. del thisdict["model"] 4. thisdict.clear()
  • 133. INTRODUCTION ï‚Ą Python Dictionary is used to store the data in a key- value pair format. ï‚Ą The dictionary is the data type in Python, which can simulate the real-life data arrangement where some specific value exists for some particular key. ï‚Ą It is the mutable data-structure. thisdict = { "brand": "Ford", "model": "Mustang", "year": 1964 }
  • 134. CREATING THE DICTIONARY ï‚Ą The dictionary can be created by using multiple key- value pairs enclosed with the curly brackets {}, and each key is separated from its value by the colon (:) ï‚Ą Python provides the built-in function dict() method which is also used to create dictionary. ï‚Ą The empty curly braces {} is used to create empty dictionary Dict = {"Name": "Tom", "Age": 22}
  • 135. ACCESSING THE DICTIONARY VALUES ï‚Ą The values can be accessed in the dictionary by using the keys as keys are unique in the dictionary. Employee = {"Name": "John", "Age": 29, "salary":25000,"Company":"GOOGLE"} print(type(Employee)) print("printing Employee data .... ") print("Name : %s" %Employee["Name"]) print("Age : %d" %Employee["Age"]) print("Salary : %d" %Employee["salary"]) print("Company : %s" %Employee["Company"])
  • 136. UPDATING DICTIONARY VALUES ï‚Ą The dictionary is a mutable data type, and its values can be updated by using the specific keys. ï‚Ą The value can be updated along with key Dict[key] = value. ï‚Ą The update() method is also used to update an existing value. # Creating an empty Dictionary Dict = {} print("Empty Dictionary: ") print(Dict) # Adding elements to dictionary one at a time Dict[0] = 'Peter' Dict[2] = 'Joseph' Dict[3] = 'Ricky' print("nDictionary after adding 3 elements: ") print(Dict) # Adding set of values # with a single Key # The Emp_ages doesn't exist to dictionary Dict['Emp_ages'] = 20, 33, 24 print("nDictionary after adding 3 elements: ") print(Dict) # Updating existing Key's Value Dict[3] = 'JavaTpoint' print("nUpdated key value: ") print(Dict)
  • 137. Python Dictionary Methods Method Description clear() Removes all the elements from the dictionary copy() Returns a copy of the dictionary fromkeys() Returns a dictionary with the specified keys and value get() Returns the value of the specified key items() Returns a list containing a tuple for each key value pair keys() Returns a list containing the dictionary's keys pop() Removes the element with the specified key popitem() Removes the last inserted key-value pair setdefault( ) Returns the value of the specified key. If the key does not exist: insert the key, with the specified value update() Updates the dictionary with the specified key-value pairs values() Returns a list of all the values in the dictionary
  • 138. DELETING ELEMENTS USING DEL KEYWORD ï‚Ą The items of the dictionary can be deleted by using the del keyword. Employee = {"Name": "John", "Age": 29, "salary": 25000,"Company":"GOOGLE"} print(type(Employee)) print("printing Employee data .... ") print(Employee) print("Deleting some of the employee data") del Employee["Name"] del Employee["Company"]
  • 139. ITERATING DICTIONARY ï‚Ą A dictionary can be iterated using for loop Employee = {"Name": "John", "Age": 29, "salary":25000,"Company" :"GOOGLE"} for x in Employee: print(x)
  • 140. PROPERTIES OF DICTIONARY KEYS ï‚Ą 1. In the dictionary, we cannot store multiple values for the same keys. If we pass more than one value for a single key, then the value which is last assigned is considered as the value of the key. ï‚Ą 2. In python, the key cannot be any mutable object. We can use numbers, strings, or tuples as the key, but we cannot use any mutable object like the list as the key in the dictionary.
  • 141. BUILT-IN DICTIONARY FUNCTIONS SN Function Description 1 cmp(dict1, dict2) It compares the items of both the dictionary and returns true if the first dictionary values are greater than the second dictionary, otherwise it returns false. 2 len(dict) It is used to calculate the length of the dictionary. 3 str(dict) It converts the dictionary into the printable string representation. 4 type(variabl e) It is used to print the type of the passed variable.
  • 142. BUILT-IN DICTIONARY METHODS SN Method Description 1 dict.clear() It is used to delete all the items of the dictionary. 2 dict.copy() It returns a shallow copy of the dictionary. 3 dict.fromkeys(iterable , value = None, /) Create a new dictionary from the iterable with the values equal to value. 4 dict.get(key, default = "None") It is used to get the value specified for the passed key. 5 dict.has_key(key) It returns true if the dictionary contains the specified key. 6 dict.items() It returns all the key-value pairs as a tuple. 7 dict.keys() It returns all the keys of the dictionary. 8 dict.setdefault(key,default= "No ne") It is used to set the key to the default value if the key is not specified in the dictionary 9 dict.update(dict2) It updates the dictionary by adding the key- value pair of dict2 to this dictionary. 10 dict.values() It returns all the values of the dictionary.