You are on page 1of 143

UNIT- I

Presented by
-------------------------
Dr Dileep Kumar M
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

Guido van Rossum 20th

Centrum Wiskunde &


Informatica (CWI) is
the National Research
Institute for
Mathematics and
Computer Science in
the Netherlands.
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


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 is not backward
compatible with Python 2.
 Python 3.7.3 - March 25, 2019
 Python 3.7.4 - July 8, 2019
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.
Python IDE - Jupyter Notebook
Environment
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.

 Itcan start with letter A to Z (or) a to z, an underscore(_)


followed by zero or more letters, underscores and digits(0-
9).

 Itdoesn’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.
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

Returns a readable version of an object. Replaces none-ascii characters


ascii() 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
Deletes the specified attribute (property or
delattr() method) from the specified object
dict() Returns a dictionary (Array)
dir() Returns a list of the specified object's
properties and methods
Returns the quotient and the remainder
divmod() when argument1 is divided by argument2
Takes a collection (e.g. a tuple) and returns
enumerate() it as an enumerate object
eval() Evaluates and executes an expression
exec() Executes the specified code (or object)
Use a filter function to exclude items in an
filter() iterable object
float() Returns a floating point number
format() Formats a specified value
frozenset() Returns a frozenset object
getattr() Returns the value of the specified attribute (property or method)

globals() Returns the current global symbol table as a dictionary

Returns True if the specified object has the specified attribute


hasattr() (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
Returns an updated dictionary of the current local symbol
locals() table

Returns the specified iterator with the specified function


map() 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
Convert an integer representing the Unicode of the specified
ord() 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

Returns a sequence of numbers, starting from 0 and


range() 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.
Identity Operators:

 The identity operators are used to decide


whether an element certain class or type.
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
 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)
del keyword

 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
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 perform oper
ation.
Operator Description Example
Repetition The repetition operator L1*2 = [1, 2, 3, 4, 1, 2, 3, 4]
enables the list elements to
be repeated multiple times.
Concatenation It concatenates the list l1+l2 = [1, 2, 3, 4, 5, 6, 7, 8]
mentioned on either side of
the operator.
Membership It returns true if a particular print(2 in l1) prints True.
item exists in a particular list
otherwise false.
Iteration The for loop is used to iterate for i in l1:
over the list elements. print(i)
Output1 2 3 4
Length It is used to get the length of len(l1) = 4
the list
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, It compares the This method is not used in the Python 3
list2) elements of both the and the above versions.
lists.
2 len(list) It is used to calculateL1 = [1,2,3,4,5,6,7,8]
the length of the list.print(len(L1))
8
3 max(list) It returns the maximum L1 = [12,34,26,48,72]
element of the list. print(max(L1))
72
4 min(list) It returns the minimum L1 = [12,34,26,48,72]
element of the list. print(min(L1))
12
5 list(seq) It converts any str = "Johnson"
sequence to the list. s = list(str)
print(type(s))
<class list>
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]
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 T1*2 = (1, 2, 3, 4, 5, 1, 2, 3, 4,
elements to be repeated multiple times. 5)
Concatenation It concatenates the tuple mentioned on T1+T2 = (1, 2, 3, 4, 5, 6, 7, 8,
either side of the operator. 9)
Membership It returns true if a particular item exists in print (2 in T1) prints True.
the tuple otherwise false
Iteration The for loop is used to iterate over the for i in T1:
tuple elements. print(i)
Output
12345

Length It is used to get the length of the tuple. len(T1) = 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
ython has two built-in methods that you can use on tuples.

Python Tuple Methods


Python has two built-in methods that you can use on tuples.

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

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
Count
Count of
of 33 in
in Tuple1
Tuple1 is:
is: 33 Count
Count of
of Python
Python in
in Tuple2
Tuple2 is:
is: 33

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)
Using Tuple Index() Method
First occurrence of 3 is 3 First occurrence of 3 after 4th index is: 5

# 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)
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_update() 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.
There is also a method called get() that will give you the same result:

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"
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
# Creating an empty Dictionary
 The dictionary is a Dict = {}
print("Empty Dictionary: ")
mutable data type, and print(Dict)

its values can be updated # Adding elements to dictionary one at a time


Dict[0] = 'Peter'
by using the specific keys. Dict[2] = 'Joseph'
Dict[3] = 'Ricky'
 The value can be updated print("\nDictionary after adding 3 elements: ")
print(Dict)

along with key Dict[key] # Adding set of values

= value. # with a single Key


# The Emp_ages doesn't exist to dictionary
Dict['Emp_ages'] = 20, 33, 24
 The update() method is print("\nDictionary after adding 3 elements: ")
print(Dict)
also used to update an
# Updating existing Key's Value
existing 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, It compares the items of both the dictionary and returns true if the
dict2) 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(variable) 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 Create a new dictionary from the iterable with the
, value = None, /) 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= "None") 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

You might also like