Class Xi Python

Download as pptx, pdf, or txt
Download as pptx, pdf, or txt
You are on page 1of 138

System Requirements

Python runs on Windows, Linux / Unix, Mac OS X,


and has been ported to the Java and .NET virtual
machines also.

No special hardware requirement


Downloading and Installation

• Log on to www.python.org
• The home page looks as .....
Click on Download Python Now Hyperlink or
Download option from the side menu..
 The Download Python Page appears. Click on the version of
Python that you want to install (Python 2.7 or Python 3.3)

 We shall be working with Python 2.7.4


Choose the required format for download
(Windows x86 MSI Installer (2.7.4))
Installation in Progress………
Installation Complete
To Start working in
Python
Welcome Screen of Python IDLE
Python Shell

Interactive Mode Script Mode


Interactive Mode

 Commands are executed directly at the prompt

Examples :-

>>> print 5+8


13

>>>6+10
16

>>>Print “Welcome to the world of Python”


Welcome to the world of Python

>>> (10+5)/3
5
Interactive Mode : Sequence of commands

Example 1 Example 2

>>> x=10 >>> a=10


>>>y=40 >>>a+1 , a-1
>>>Z=x+y (11,9)
>>>print Z
50

 to repeat the prior command in the


interactive window , use to scroll
backward through the command history
and key to scroll forward.
To leave the interpreter and
return to shell

• ^D (Ctrl+D) or
• Type quit ()
Script Mode
File New
Type Python program in a file
 Save it . Default extension is .py
 then use interpreter to execute the
contents from the file by
 Can use Run option or press F5
 type the function name at command
prompt
Variables / Objects in Python

Every object/variable has

Identity Type Value


Identity

 Variable’s address in memory

 does not change once it has been


created.
The id() command gives the identity number of a
variable, it’s unique for each variable
Syntax : id(variable)
Example :
>>>id(x)
4325671
Type (Data Type)

A set of values and the


allowable operations on
those values.
Data types supported by Python
Number Data Type
1.Number
1.Integer & Long
Example
>>>a=10
>>>b=1234567L
>>>print a,b
10, 123456L
2. Floating Point ‘j’ i
su
Example i m agi sed f
nar or
>>>y=12.89 yp
>>>print y art
12.89
3. Complex
Example
>>>x= 1+0j
>>>print x.real , x.imag
1.0, 0.0
Type Conversion
• Automatic type conversion from int to float if required
>>> f=78.90876
>>> i=9
>>> i=i+f
>>> print i
87.90876
• very big integer is automatically converted to
long
• To know the datatype of a variable use type()
>>> var=1234
>>> type(var)
<type 'int'>
>>> var=var*98765432
>>> type(var)
<type 'long'>
Integers (contd)
4. Boolean
• Boolean Type consists of a two values : True & False

• Boolean True is non zero, non null and non empty

Example
>>> flag=True
>>> type(flag)
<type 'bool'>
>>> flag=False
>>> type(flag)
<type 'bool'>
2. None
used to signify the absence of value / false in a situation

3.Sequence

• Ordered collection of items , indexed by integers

• Combination of mutable and non mutable data types


Sequence Data Type
String Lists Tuple

• An ordered • A sequence of • are sequence of


sequence of letters values of any type values of any type
and characters
• Values in the list • Are indexed by
• Enclosed in “ “ or ‘ are called items and integers
‘ are indexed
• Are immutable
• Are immutable • Are mutable
• Are enclosed in ()
Example • Are enclosed in [] Example
Example (2,4)
>>>a=“Ram” [‘spam’ , 20, 13.5]
Data Types (contd.)
4.Sets :
• an unordered collection of values of any type
• No duplicate entries allowed
• Are immutable
Example
S=set([1,2,3,4])

5.Mapping
• an unordered data type for eg: dictonaries

• A dictonary can store any number of Python objects


enclosed in curly brackets
Example :
D= {1:’a’ , 2:’b’, 3:’c’}
Value of an object(variable)

to bind value to a variable assignment operator(=)


can be used

Example :

>>>x=1256
Mutable and Immutable
Variables

Mutable Variable :

one whose value may change in place

Immutable Variable :

# Change of value will not happen in place.

# Modifying an immutable variable will rebuild the


same variable.
Example
>>>x=5
will create a value 5 referenced by x

x 5

>>>y=x
will make y refer to 5 of x

x
5
y
>>>x=x+y
RHS results to 10
value assigned to LHS (x)
x rebuilds to 10
x 10

y 5
Example
x = something # immutable type
y=x
print x
// some statement that operates on y
print x # prints the original value of x 
x = something # mutable type
y=x
print x
// some statement that operates on y
print x # might print something different
Example
Immutable variable - x
x = 'foo'
y=x
print x # foo
y += 'bar'
print x # foo
 Mutable Variable - x
x = [1, 2, 3]
y=x
print x # [1, 2, 3]
y += [3, 2, 1]
print x # [1, 2, 3, 3, 2, 1]
Points to remember about variables……

• Are created when they are first assigned a value

• Refer to an object

• Must be assigned a value before using them in


any expression

• Keywords cannot be used as variable names


Operators

Arithmetic Assignment

Relational Logical

Operators when applied to operands form an expression


Arithmetic Operators
Symbol Description Example 1 Example 2
>>>55+45 >>> ‘Good’ + ‘Morning’
+ Addition
100 GoodMorning
>>>55-45 >>>30-80
- Subtraction
10 -50
>>>55*45 >>> ‘Good’* 3
* Multiplication
2475 GoodGoodGood

>>>17/5
3 >>>28/3
/ Division*
>>>17/5.0 9
3.4
Remainder/ >>>17%5 >>> 23%2
% 1
Modulo 2
>>>2**8
>>>2**3 256
** Exponentiation
8

>>>7.0//2 >>>3/ / 2
// Integer Division 1.0
3.0
Relational Operators
Symbol Description Example 1 Example 2
>>>7<10
True >>>‘Hello’< ’Goodbye’
>>> 7<5 False
< Less than False >>>'Goodbye'< 'Hello'
>>> 7<10<15 True
True
>>>7>5 >>>‘Hello’> ‘Goodbye’
True True
> Greater than >>>10<10 >>>'Goodbye'> 'Hello'
False False
>>> 2<=5 >>>‘Hello’<= ‘Goodbye’
True False
<= less than equal to >>> 7<=4 >>>'Goodbye' <= 'Hello'
False True
>>>10>=10 >>>’Hello’>= ‘Goodbye’
True True
>= greater than equal to >>>10>=12 >>>'Goodbye' >= 'Hello'
False False
>>>10!=11 >>>’Hello’!= ‘HELLO’
True True
! =, <> not equal to >>>10!=10 >>> ‘Hello’ != ‘Hello’
False False
>>>10==10 >>>“Hello’ == ’Hello’
True True
== equal to >>>10==11 >>>’Hello’ == ‘Good Bye’
False False
Logical Operators

Symbol Description

If any one of the operand is true,


or
then the condition becomes true.

If both the operands are true,


and
then the condition becomes true.

Reverses the state of


not
operand/condition.
Assignment Operator
Symbol Description Example Explanation
>>>x=12* *we will use it as initial
Assigned values from right side
= >>>y=’greeting value of x for following
operands to left variable
s’ examples.

Added and assign back the result to left Will change the value of x to
+= >>>x+=2
operand 14

Subtracted and assign back the result


-= x-=2 x will become 10
to left operand

Multiplied and assign back the result to


*= x*=2 x will become 24
left operand
Divided and assign back the result to
/= x/=2 x will become 6
left operand
Taken modulus using two operands and x will become 0
%= x%=2
assign the result to left operand
Performed exponential (power) x will become 144
**= calculation on operators and assign x**=2
value to the left operand
Performed floor division on operators x / /= 2 x will become 6
//=
and assign value to the left operand
Points to remember about operators...

Same operator may perform a different


function depending on the data type of the
operands

 Division operator ( / )behaves differently with


integers and floats

 Multiplication operator( * ) and addition operator


( + ) behave differently on integers and strings
Expressions and Statements
Expression:
A consists of values i.e. constants or variables
and operators
 Examples
2+x
50.8/4+(20-4)
Statement:
A unit of code that a python interpreter can
execute
 Examples
>>>print 90 # print statement
>>>x=60+40 # addition/assignment statement
Points to remember about Expressions…….
In case of operands with different data types ,
implicit typecasting occurs.
 Examples
>>> print 0.8/4+(20-4)
16.2

All integers are promoted to floats and the final


result of the expression is a float value

 In case of multiple sub expressions in a single


expression , general precedence rules apply
Precedence of Operators
Operator Description
** Exponentiation (raise to the power)

+,- unary plus and minus

Multiply, divide, modulo and floor


* , /, %, //
division
+,- Addition and subtraction
relational operators for
<, <=, >, >=
comparision
==, != Equality operators
%=,/ =, //=, - = , + =, * = , ** = Assignment operators
not; and; or Logical operators
While working in Python……
 Write one python statement per line (Physical Line).

 Comment starts with ‘#’ and ends at the end of a line.

 When entering statement(s) in interactive mode, an


extra blank line is treated as the end of the indented
block.

 White space in the beginning of line is part of


indentation, elsewhere it is not significant

If a statement runs into multiple physical lines , a ‘ \’


is used at the end of a physical line.
Input-Output Facility
• Helps to interact with end user to accomplish
the desired task.
• Functions available for input are :

 raw_input()

 input ( )
raw_input()
• Syntax
raw_input ([prompt])

• e.g. (in interactive mode)


>>>x=raw_input (‘Enter your name : ’)
Enter your name : ABC
Concatenation of strings using
raw_input( ) method

>>>Input1=raw_input(“Enter the first Name: ”)


Enter the first Name: DPS

>>>Input2=raw_input(“Enter the second Name: ”)


Enter the second input: Gurgaon

>>>Input1+Input2
>>>’DPS Gurgaon’
Addition of two numbers using raw_input( )
method

>>>Input1=raw_input(“Enter the first input:”)


Enter the first input: 78

>>>Input2=raw_input(“Enter the second input:”)


Enter the second input: 100

>>>Input1+Input2 d esired
t th e
is i s no
>>>’78100’ o ps! T h
O
ut.
outp
Addition of two numbers using
raw_input( ) method

>>>Input1=int(raw_input(“Enter the first input:”))


Enter the first input: 78

>>>Input2=int(raw_input(“Enter the second input:”))


Enter the second input: 100

>>>Input1+Input2
>>>178
raw_input() –Numeric data
• typecast the string data accepted from user to appropriate
Numeric type.

• e.g.
>>>y=int(raw_input(“enter your roll no”))

• E.g.
• >>>z = float(raw_input(“ enter the float value”)
input()
• Syntax
input ([prompt])

• Eg:
x= input (‘enter data:’)
Enter data: 2+ 1/2.0
Will supply 2.5 to x
Output
• For output in Python we use ‘print ’.
• Syntax:
print expression/constant/variable

• Example:
>>> print “Hello”
Hello
>>> print 5.5
5.5
>>> print 4+6
10
Functions
A function is named sequence of statement(s) that
performs a computation.

Functions can be categorized as belonging to


• Modules
• Built in
• User Defined
Module

• A module is a file containing Python definitions.


• To use module(s) in the program, programmer needs to
import the module.
• Once you import a module, you can refer (use) to any of it
functions or constant in your code.
• Commands to import a module are:
• import
• from
Import:
• Syntax :
import modulename1 [,modulename2, ---------]

Eg:
>>> import math

To use a function, you will specify the module name and


name of the function separated by dot (.).

This format is also known as dot notation.


>>> value= math.sqrt (25)
From statement
• From statement is used to get a specific
function in the code instead of complete file.

• Syntax
>>> from modulename import functionname
[, functionname…..]
e.g
>>> from math import sqrt
Value = sqrt (25)
Some Functions from Math module
Name of the Description Example
function

It returns base-10 math.log10(100.12) :


log10( x ) logarithm of x for x 2.00052084094
> 0, where x is a math.log10(100.72) :
numeric expression. 2.0031157171

It returns the value


pow( x, y ) of x raised to y, math.pow(2, 4) :
where x and y are 16.0
numeric expressions.
Some Functions from Math module
Name of the Description Example
function

exp( x ) It returns exponential math.exp(100.12) :


of x: ex, where x is a 3.03084361407e+43
numeric expression.

It returns natural math.log(100.12) :


log( x ) logarithm of x, for x > 4.60636946656
0, where x is a math.log(100.72) :
numeric expression. 4.61234438974
Some Functions from Random module
Name of the Description Example
function

random ( ) It returns a random >>>random.random ( )


float x, such that 0.309090465205
0 ≤ x<1

randint (a, b) It returns a float x >>>random.randint (1,10)


between a & b such 5
that
a≤x≤b
Some Functions from Random module
Name of the Description Example
function

uniform (a,b) It returns a >>>random.uniform(5, 10)


floating point 5.52615217015
number x, such
that
a <= x < b
randrange It returns a >>>random.randrange(100,1000,3)
([start,]stop random item from 150
[,step]) the given range
Some Functions from Datetime module
Name of the Description Example
function

MAXYEAR is Is valid maximum value >>>import datetime


constant of year. It is set to 9999 >>>value=datetime.MAXYEAR
>>> value
9999

MINYEAR is Is valid minimum value >>>import datetime


constant of year. It is 1 >>> value=datetime.MINYEAR
>>> value
1
Some Functions from Datetime module
Name of the Description Example
function

datetime Returns value of >>>value=datetime.datetime.today()


current date and >>> print value
time 2013-04-19 11:25:26.609000

date Returens only date >>> value=datetime.date.today()


attributes >>> print value
2013-04-19
Composition
• Is art of combining simple function(s) to build more
complicated ones,
• result of one function is used as the input to another.

Eg. Suppose we have two functions fn1 & fn2, such that
a= fn2 (x)
b= fn1 (a)
 
then call to the two functions can be combined as
b= fn1 (fn2 (x))

Eg:
degrees=270
math.sin (degrees/360.0 ° *2*math.pi)
Built in Function
• Built into Python and can be accessed by Programmer.

• No need to import any module (file).

Examples
(i) >>> range(10)
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> range(1, 11)
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

(ii) >>> b= ‘Hello’


>>> len (b)
5
Examples Built -in- Functions
Name of the Description Example
function

cmp( x, y ) It returns the sign of >>>cmp(80, 100) :


the difference of two -1
numbers: -1 if x < y, 0 >>>cmp(180, 100) :
if x == y, or 1 if x > y, 1
where x and y are
numeric
variable/expression.
abs (x) It returns distance >>>abs(-45) :
between x and zero, 45
where x is a numeric >>>abs(119L) :
expression.
119
Examples Built -in- Functions
Name of the Description Example
function

max( x, y, z, .... ) It returns the largest of >>>max(80, 100,


its arguments: where 1000) : 1000
x, y and z are numeric >>>max(-80, -20, -
variable/expression. 10) : -10

min( x, y, z, .... ) It returns the smallest >>> min(80, 100,


of its arguments; 1000) : 80
where x, y, and z are >>> min(-80, -20, -
numeric
variable/expression. 10) : -80
User Defined Functions:
• These functions can be combined to form module which can be
used in other programs by importing them.

• To define a function keyword ‘def’ is used. After the keyword


comes an identifier i.e. name of the function, followed by
parenthesized list of parameters and the colon which ends up the
line. Next follows the block of statement(s) that are the part of
function.

• Example
def area (radius):
a = 3.14*radius**2
return a
Function call
>>> print area (5)
Scope of variables
The part of the program where a variable can be used is
known as Scope of variable

Two types of scopes :


Global Scope


Local Scope
Global Scope

With global scope, variable can be used
anywhere in the program
eg:
x=50
def test ( ):
print “inside test x is “, x
print “value of x is “, x

Output:
inside test x is 50
value of x is 50
Local Scope

With local scope, variable can be used only within the
function / block that it is created .
Eg:
X=50
def test ( ):
y = 20
print ‘value of x is ’, X, ‘ y is ’ , y
print ‘value of x is ’, X, ‘ y is ‘ , y

On executing the code we will get


Value of x is 50 y is 20

The next print statement will produce an error, because the variable y is
not accessible outside the def()
More on Scope of Variables
To access global variable inside the function prefix
keyword global with the variable
Eg:

x=50
def test ( ):
global x =5
y =2
print ‘value of x & y inside the function are ‘ , x , y
print ‘value of x outside function is ‘ ‘,

This code will produce following output:


Value of x & y inside the function are 5 2
Value of x outside the function is 5
Default argument
A default argument is a function parameter that has a default
value provided to it. If the user does not supply a value for this
parameter, the default value will be used. If the user does supply a
value for the default parameter, the user-supplied value is used.

Eg.
def greet (message, times=1):
print message * times

>>> greet (‘Welcome’) # function call with one argument value


>>> greet (‘Hello’, 2) # function call with both the argument values.

Output:
Welcome
HelloHello
Fruitful and Void Functions

Fruitful functions return some value
Example:
>>>x=math.sqrt(25)
>>>print x


Void Functions returns no value
Example:
def greet (message, times=1):
print message * times
Docstrings

Enclosed in triple quotes.

What function does (without How it does) i.e. summary of its purpose

Type of parameters it take

Effect of parameter on behaviour of functions, etc

Eg:
def area (radius):
“””Calculates area of a circle.

require an integer or float value to calculate area.


returns the calculated value to calling function “””

area = radius**2
return area
DocString Conventions


The first line of docstring starts with capital
letter and ends with a period (.)


Second line is left blank (it visually
separates summary from other
description).


Other details of docstring start from 3rd line.
Control Flow Structure:
• Sequence

• Selection
- if
- if …else
- if…elif….else

• Looping
- for
- while
If Statement
• if x > 0:
print ‘x is positive’

• if x > y:
print ‘x is big’
else:
print ‘y is big’

• if x > 0:
print ‘x is positive’
elif x<0:
print ‘x is negative’
else:
print ‘x is zero’
Examples on if using logical operators

"""program to input three integers and


print the largest of three. """

def largest():
a=input("Enter the first value")
b=input("Enter the second value")
c=input("Enter the third value")

if(( a>b) and(a>c)):


print " a is Greatest"
elif(( b>c) and(b>a)):
print " b is Greatest"
else:
print "c is greatest"
while statement
Syntax

while condition:
STATEMENT BLOCK 1
 [else:
STATEMENT BLOCK 2]
while statement
• Eg:-
i=1
while (i <=10):
print i,
i +=1
else:
# to bring print control to next line
print “coming out of loop”

Will result into


1 2 3 4 5 6 7 8 9 10
coming out of loop
For statement
Syntax

for TARGET- LIST in EXPRESSION-LIST:


STATEMENT BLOCK 1
[else: # optional block
STATEMENT BLOCK 2]
 
For statement
• E.g. 1:
loop to print value 1 to 10
for i in range (1, 11, 1):
print i,

Execution of the loop will result into


1 2 3 4 5 6 7 8 9 10
E.g. 2:
for letter in ‘Python’:
print ‘Current Letter’ ,letter

On execution, will produce the following:


Current Letter: P
Current Letter: y
Current Letter: t
Current Letter: h
Current Letter: o
Current Letter: n
Break
• Used to unconditionally jump out of the loop.
• It terminates the execution of loop.
• Break can be used in while loop and for loop.
• Is mostly required, when because of some external condition,
we need to exit from a loop.

E.g.:
for letter in ‘Python’:
if letter == ‘h’:
break
print letter
Example - Break
"""A program to check whether a number is prime
or not"""
def prime():
number=input("Enter the value")
for i in range(2,number/2,1):
if(number % i == 0):
print " not prime"
break
else:
print " prime"
Continue
• Used to skip the rest of the statements of the
current loop block and to move to next
iteration, of the loop.
• Continue will return back the control to the
beginning of the loop.
• Can be used with both while & for.
Eg:
for letter in ‘Python’:
if letter == ‘h’:
continue
print letter,
Output
Pyton
Strings
• A set of characters enclosed in single /
double / triple quotes

• Are indexed, immutable data types

Example:
>>> str='honesty'
>>> str[2]='p'
TypeError: 'str' object does not support item
assignment
Initializing Strings
Examples
>>>print ‘ A friend in need a friend indeed’
A friend in need a friend indeed

>>>print “A room without books is like a body without a soul.”

A room without books is like a body without a soul.

>>>life=”””\” Live as if you were to die tomorrow.

Learn as if you were to live forever.\”

---- Mahatma Gandhi “””


Traversing a string
Traversing a string means accessing all the
elements of the string one after the other by
using the subscript.

A string can be traversed using:


for loop


while loop.
Traversing a string
Using for loop Using while loop

A=’Welcome’ A=’Welcome’
>>>for i in A: >>>i=0
print i >>>while i<len(A):
W print A[i]
e i=i+1
l W
c e
o l
m c
e o
m
e
Strings operations
Operator Description Example
+ (Concatenation) The + operator joins the >>> ‘Save’+’Earth’
text on both sides of the ‘Save Earth’
operator

* (Repetition ) The * operator repeats >>>3*’Save Earth ’


the string on the left hand ‘Save Earth Save
side times the value on Earth Save Earth ’
right hand side.

in (Membership) The operator displays 1 if >>>A=’Save Earth’


the string contains the >>>’Save’ in A
given character or the True
sequence of characters. >>’SE’ in A
False
Strings operations(contd.)
Operator Description Example
not in The operator displays 1 if >>>’SE’ not in ‘Save Earth’
the string does not contain True
the given character or the >>>’Save ‘ not in ‘Save
sequence of characters. Earth’
False
Strings Slicing
Syntax:

Slice[n : m]

Description
The Slice[n : m] operator extracts sub parts from the
strings.

Example

>>>A = ’Save Earth’


>>> print A[1:3]
av
More on Slicing
Consider the given figure :

String A S a v e E a r t h
Positive Index 0 1 2 3 4 5 6 7 8 9
Negative Index -10 -9 -8 -7 -6 -5 -4 -3 -2 -1

Examples

>>>print A[3:]
‘e Earth’

>>>print A[:3]
Sav

>>>print A[:]
‘Save Earth’

>>>print A[-2:]
‘th’
String Functions
Function Description Example
capitalize Returns the exact copy of the >>> str=’welcome’
string with the first letter in >>>print str.capitalize()
upper case
Welcome

isdigit Returns true if the string >>>print str.isdigit()


contains only numbers. False
Otherwise it returns false.
lower Returns the exact copy of the >>>A=‘Save Earth’
string with all the letters in >>>print A.lower()
lowercase. ‘save earth’
islower Returns true if the string is in >>>print str.islower()
lowercase. True

isalpha Returns true if the string >>> 'Click123'.isalpha()


contains only letters. Otherwise False
return false. >>> 'python'.isalpha()
True
String Functions(contd.)
Function Description Example
isupper() Returns true if the string is in >>>str=‘Welcome’
uppercase. >>>print str.isupper()
False
upper() Returns the exact copy of the >>>print str.upper()
string with all letters in WELCOME
uppercase.
find(sub[, start[, end]]) used to search the first >>> str='mammals'
occurrence of the substring in >>> str.find('ma')
the given string. It returns the 0
index at which the substring >>> str.find('ma',2)
starts and returns -1 if the 3
substring does not exist. >>> str.find('ma',2,4)
-1

isalnum() Returns true if the string >>> str='Save Earth'


contains only letters and digit >>> str.isalnum()
and returns false if the string False
contains any special character >>>'SaveEarth'.isalnum()
like _ , @,#,* etc. True
String Functions(contd.)

Function Description Example

lstrip() Returns the string after removing the >>> print str
space(s) on the left of the string. Save Earth
If a string is passed as argument to >>> str.lstrip()
the lstrip() function, it removes those 'Save Earth'
characters from the left of the string. >>> str='Teach India
Movement'
>>> print str.lstrip("Te")
ach India Movement

rstrip() Returns the string after removing the >>> str='Teach India
space(s) on the right of the string Movement’
>>> print str.rstrip()
Teach India Movement
A Sample Program
Program to count no of ‘p’ in the given string .

def lettercount():
word = 'python practice'
count = 0
for letter in word:
if letter == 'p':
count = count + 1
print count
Output
2
Lists
Lists

Like a String, List also is, sequence data type.

In a string we have only characters but a list
consists of data of multiple data types

It is an ordered set of values enclosed in
square brackets [].

We can use index in square brackets []

Values in the list are called elements or items.

A list can be modified, i.e. it is mutable.
Lists (contd.)
List index works the same way as String index :

An integer value/expression can be used as index

An Index Error appears, if you try and access element


that does not exist in the list

An index can have a negative value, in that case


counting happens from the end of the list
Lists - Examples
i) L1 = [1,2,3,4] list of 4 integer elements.

ii) L2 = [“Delhi”, “Chennai”, “Mumbai”]


list of 3 string elements.

iii) L3 = [ ] empty list i.e. list with no element

iv) L4 = [“abc”, 10, 20] list with different types of elements


Creating a List
(i) By enclosing elements in []
For Example :
L=[1,2,3,4]

(ii) Using other lists


For Example :

>>>L=[1,2,3,4]
>>>L5=L # L5 is created as a copy of L

>>>L6=L[0:2] # L6 will have first two elements of L


Creating a List (contd.)
(iii) By List Comprehension – a short hand for
creating lists
For Example :

>>> n= 5 >>> A=[1,2,3]


>>>B=[value*3 for value in A]
>>>L=range(n) >>>print B
>>>print L [3,6,9]
[0,1,2,3,4]
Creating a List (contd.)
(iv) By using Built in function
For Example :

>>> L= list() # will create an empty list

>>>L= list[(1,2,3,4)]
>>>print L
[1,2,3,4]
List Slices
New_list= L[start:stop:step]

L1=[1,2,3,4]
Print(L1[1:4:2])
Ans: [2,4]

• start, stop and step are optional


• value of start is inclusive while stop is not
inclusive
• default value of step is 1
List Slices (Examples)

• >>> L=[10,20,30,40,50]

>>> print L[0:2] #start=0 , stop=2, step=1 (default)


[10, 20]

• >>> print L[3:] #start =3, stop= 4, step=1(default)


[40, 50]

• >>> print L[:3] # start=0, stop=3, step=1(default)


[10, 20, 30]

• >>> print L[0:5:2]#start=0, stop=5 (to include the last


element ), step=2
[10, 30, 50]
Traversing a List
• Using while loop
L=[1,2,3,4]
i=0
while i < 4:
print L [i],
i+=1

Output
1234
Traversing a List (contd)

Using for loop

L=[1,2,3,4,5] L1=[1,2,3,4,5]
for i in L:for i in range (5):
print i, print L1 [i],

Output: Output:
1 2 3 4 51 2 3 4 5
append method
 to add one element at the end of the list
Example:
>>> l=[1,2,3,4]
>>> print l
[1, 2, 3, 4]
>>> l.append(5)
>>> print l
[1, 2, 3, 4, 5]
extend Method
To add a list at the end of another list

Example
>>> l1=[10,20,30]
>>> l2=[100,200,300]
>>> l1.extend(l2)
>>> print l1
[10, 20, 30, 100, 200, 300]
>>> print l2
[100, 200, 300]
Updating list elements
Can update single or multiple elements

Example

>>> l1=[10,20,30, 40,50]


>>>l1[1]=[1]
>>>print l1
[10,1,30,40,50] #2nd element is updated

>>>l1[1:2]=[90,100]
>>>print l1
[10,90,100,40,50] #2nd and 3rd element is updated
Use of + and * operators
+ operator – concatenates two lists

Example

>>> L1=[10,20,30]
>>>L2=[40,50]
>>>L3=L1+L2
>>>print L3
[10,20,30,40,50]
Use of + and * operators
* operator – repetition of lists
Example
>>> L1=[10,20,30]
>>>L2= L1*3
>>>print L2
[10,20,30,10,20,30,10,20,30]

>>>[‘Hi’]*4
[‘Hi’,’Hi’,’Hi’,’Hi’]
Deleting Elements from list

• pop() – to remove the element from given index

• del() – to remove more than one element with slicing

• remove() - to remove the element without the index


Deleting Elements from list

• Examples
>>> l=[10,20,30,40,50]
>>> l.pop() #pop without index deletes the last
element i.e. 50
50
>>> l.pop(1)
20 #deletes 2nd element i.e. 20
>>> l.remove(10) #deleted 10 i.e. 1st element
>>> print l
[30, 40]
Deleting Elements from list

• Example
>>> l=[1,2,3,4,5,6,7,8]
>>> del l[2:5] #deletes from 3rd to 6th element

>>> print l
[1, 2, 6, 7, 8]
insert method
used to add element(s) in between the list
Syntax
list.insert(index,item)
Example
>>> l=[10,20,30,40,50]
>>> l.insert(2,25)
>>> print l
[10, 20, 25, 30, 40, 50]
sort() and sorted() methods
sort(): Used to arrange the list in ascending order in place
Example:
>>> l=[10,8,4,7,3]
>>> l.sort()
>>> print l
[3, 4, 7, 8, 10]

sorted(): returns the new sorted list


Example:
>>> L1= sorted(l)
>>> print L1
[3, 4, 7, 8, 10]
reverse() method

used to reverse the list.


Example:

>>>l= [3, 4, 7, 8, 10]


>>> l.reverse()
>>> print l
[10, 8, 7, 4, 3]
Passing list as argument to
a function

• Any change made in the function is


reflected in the original list.

• Operations which create a new list will


not modify the original list.
Passing list as argument to
a function

Example
def test(L1):
for I in range(len(L1)):
L1[i]+=10
>>>x=[1,2,3,4,5]
>>>test(x)
>>>print x
[11,12,13,14,15]
An Example
n=input("Enter total number of elements")
l=range(n)
for i in range(n):
l[i]=input("enter element")
print "All elements in the list on the output screen"
for i in range(n):
print l[i]
Output
Enter total number of elements5
enter element10
enter element20
enter element30
enter element40
enter element50
All elements in the list on the output screen
10
20
30
40
50
DICTIONARIES
Dictionaries
• General form of a list that is created by using curly
brackets { }

• Index values can be any other data type and are called
keys.

• Each element is accessed (or indexed) by a unique key.

• Often, the key will be used as a string as it is easy to


recall.

• Extremely useful data storage construct for storing and


retrieving all key value pairs
Key Value Pair
• Each key maps a value

• The association of a key and a value is called a key-value pair.

Syntax:

my_dict = {'key1': 'value1','key2': 'value2','key3': 'value3'…'keyn': 'valuen’}


Month={“Jan”:31,”feb”:28,”Mar”:31}
Print(Month[“feb”])
Example
>>> A={1:"one",2:"two",3:"three"}
>>> printA[2]
{1: 'one', 2: 'two', 3: 'three'}
 
Creation of a Dictionary:
(i) dict ( ) is used to create a new dictionary with no
items

Example
>>> D={}
>>> print D
{}
Adding elements in a Dictionary:

• Use square brackets for accessing and initializing dictionary


values.
 
Example H={“hardware”:”tablet”}
>>> H["one"]="keyboard"
>>> H["two"]="Mouse"
>>> H["three"]="printer"
>>> H["Four"]="scanner"
>>> print H
{“hardware”:”tablet”,'Four': 'scanner', 'three': 'printer',
'two': 'Mouse', 'one': 'keyboard'}
Traversing a dictionary

• By using ‘for-loop’.

Example
H={'Four': 'scanner', 'three': 'printer', 'two': 'Mouse', 'one':
'keyboard'}
for i in H:
print(I,”:”, H[i])
 
 Output:
Four: scanner three: printer two: Mouse
one:keyboard
Appending values to the
dictionary
• To add only one element to the dictionary
 
Syntax:
Dictionaryname[key]=value
 
Example:
>>> a={"mon":"monday","tue":"tuesday","wed":"wednesday"}
>>> a["thu"]="thursday"
>>> print a
{'thu': 'thursday', 'wed': 'wednesday', 'mon': 'monday', 'tue':
'tuesday'}
>>> 
Update()
( Merging Dictionaries)
update ( ) method merges the keys and values of one
dictionary into another and overwrites values of the same key.

Syntax:
Dic_name1.update(dic_name2)
Using this dic_name2 is added with Dic_name1.

Example:
>>> d1={1:10,2:20,3:30}
>>> d2={4:40,5:50}
>>> d1.update(d2)
>>> print d1
{1: 10, 2: 20, 3: 30, 4: 40, 5: 50}
 
del()

To remove an item from the existing dictionary

Syntax:
del dicname[key]

Example:
>>>A={"mon":"monday","tue":"tuesday","wed":"wednesda
y","thu":"thursday"}
>>> del A["tue"]
>>> print A
{'thu': 'thursday', 'wed': 'wednesday', 'mon': 'monday'}
>>> 
Dictionary Functions
(i) cmp()
• used to check whether the given dictionaries are same or not.

If both are same, it will return ‘zero’


If the first dictionary is having more number of items then it will return 1,
otherwise return -1.
Syntax:
cmp(d1,d2) #d1and d2 are dictionary.
 Example:
>>>D1={'sun':'Sunday','mon':'Monday','tue':'Tuesday','wed':'Wednesday','thu':'Thursday','fri':'Friday','sat':'
Saturday'}
>>>
D2={'sun':'Sunday','mon':'Monday','tue':'Tuesday','wed':'Wednesday','thu':'Thursday','fri':'Friday','sat':'Sat
urday'}
>>> D3={'mon':'Monday','tue':'Tuesday','wed':'Wednesday'}
>>> cmp(D1,D3) #both are not equal
1
>>> cmp(D1,D2) #both are equal
0
>>> cmp(D3,D1)
-1
Dictionary Functions(contd.)

(ii) len()
 
It returns number of key-value pairs in the given dictionary.
 
Syntax:
len(d) #d dictionary

Example:

>>> H={'Four': 'scanner', 'three': 'printer', 'two': 'Mouse',


'one': 'keyboard'}
>>> len(H)
4
Dictionary Functions(contd.)

(iii) clear()
 
It removes all items from the particular dictionary.
 Syntax:
d.clear( ) #d dictionary
 
 Example
>>> D={'mon':'Monday','tue':'Tuesday','wed':'Wednesday'}
>>> print D
{'wed': 'Wednesday', 'mon': 'Monday', 'tue': 'Tuesday'}
>>> D.clear( )
>>> print D
{}
Dictionary Functions(contd.)

(iV) has_key( )

It returns ‘True’, if dictionary has a key, otherwise it returns


‘False’.
 Syntax:
 D.has_key(k) #D dictionary and k key
Example
>>>
D={'sun':'Sunday','mon':'Monday','tue':'Tuesday','wed':'Wednesday','thu'
:'Thursday','fri':'Friday','sat':'Saturday'}
>>> D.has_key("fri")
True
>>> D.has_key("aaa")
False
>>> 
 
Dictionary Functions(contd.)

(iV) items( )
It returns the content of dictionary as a list of key and value in
the form of a tuple.(not in any particular order)
 
Syntax:
 D.items() # D dictionary
Example
>>>D={'sun':'Sunday','mon':'Monday','tue':'Tuesday','wed':'
Wednesday','thu':'Thursday','fri':'Friday','sat':'Saturday'}
>>> D.items()
[('wed', 'Wednesday'), ('sun', 'Sunday'), ('thu', 'Thursday'),
('tue', 'Tuesday'), ('mon', 'Monday'), ('fri', 'Friday'), ('sat',
'Saturday')]
Dictionary Functions(contd.)

(iV) values()
It returns the values from key-value pairs(not in any particular
order)
 
Syntax:
 D.items() # D dictionary
Example
>>>D={'sun':'Sunday','mon':'Monday','tue':'Tuesday','wed':'
Wednesday','thu':'Thursday','fri':'Friday','sat':'Saturday'}
>>> D.values()
['Wednesday'), 'Sunday', 'Thursday’, 'Tuesday','Monday',
'Friday’, 'Saturday’]

You might also like