Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
244 views

Functions: Defining A Function, Calling A Function, Types of Functions

This document provides an overview of functions in Python, including defining, calling, and different types of functions. It discusses function arguments like required arguments, keyword arguments, default arguments, and variable-length arguments. It also covers global and local variables, and other function-related topics like anonymous functions, recursion, and built-in functions like filter, map, and reduce.

Uploaded by

naman jaiswal
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
244 views

Functions: Defining A Function, Calling A Function, Types of Functions

This document provides an overview of functions in Python, including defining, calling, and different types of functions. It discusses function arguments like required arguments, keyword arguments, default arguments, and variable-length arguments. It also covers global and local variables, and other function-related topics like anonymous functions, recursion, and built-in functions like filter, map, and reduce.

Uploaded by

naman jaiswal
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 97

UNIT – II

Contents:
 Functions
Defining a Function, Calling a Function, Types of Functions,
Function arguments, Anonymous Functions, Global and Local
Variables
 String Manipulation
Accessing Strings, Basic Operations, String slices, Function and
Methods
 Lists
Accessing list, Operations, working with lists Function and
Methods
 Tuple
Accessing tuples, Operations , working with tuples
 Dictionaries
Accessing Values in Dictionaries, working with
dictionaries, ROHITA
Properties
YAMAGANTIFunctions and Methods
Defining a Function:

A function is a group of statements that exist within a program


for the purpose of performing a specific task.

Defining and Calling a Function


To create a function you write its definition. Here is the general
format of a function definition in Python:

Syntax:
def function_name():
statement
statement
etc.
ROHITA YAMAGANTI
 The first line is known as the function header. It marks the
beginning of the function definition.
 The function header begins with the key word def, followed by the
name of the function, followed by a set of parentheses, followed by
a colon.
 Beginning at the next line is a set of statements known as a block.
A block is simply a set of statements that belong together as a
group.

EX
def message():
print('I am Arthur,')
print('King of the Britons.')

 This code defines a function named message. The message


function contains a block with two statements. Executing the
function will cause these statements to execute.
ROHITA YAMAGANTI
Calling a Function
 function definition specifies what a function does, but it does not
cause the function to execute. To execute a function, you must call
it.
 When a function is called, the interpreter jumps to that function
and executes the statements in its block.
 When the end of the block is reached, the interpreter jumps back
to the part of the program that called the function

EX: def message():


print("I am a Student")
print("I am learning Python Programming Language")
message() # call the message function

Program Output:
I am a Student
I am learning Python Programming Language
ROHITA YAMAGANTI
Types of Functions
Basically, we can divide functions into the following two
types:
Built-in functions - Functions that are built into Python.
User-defined functions - Functions defined by the users
themselves.

ROHITA YAMAGANTI
Python Built -in Function

The Python interpreter has a number of functions that are


always available for use. These functions are called built-in
functions.
For example, print() function prints the given object to the
standard output device (screen) or to the text stream file.

In Python 3.6 (latest version), there are 68 built-in functions.


They are listed below alphabetically along with brief
description.

ROHITA YAMAGANTI
What are user-defined functions in Python?
Functions that we define ourselves to do certain specific task are referred as user-defined
functions..
Functions that readily come with Python are called built-in functions.
If we use functions written by others in the form of library, it can be termed as library
functions.
All the other functions that we write on our own fall under user-defined functions.
So, our user-defined function could be a library function to someone else.

Advantages of user-defined functions


User-defined functions help to decompose a large program into small segments which
makes program easy to understand, maintain and debug.

If repeated code occurs in a program. Function can be used to include those codes and
execute when needed by calling that function.

Programmars working on large project can divide the workload by making different
functions.

ROHITA YAMAGANTI
ROHITA YAMAGANTI
1. Fruitful function
2. void function
1. Fruitful function:
 A function that returns a value
 All built-in functions, math functions produce results.
 Calling the function generates a value, which we usually assign to a
variable or use as part of an expression.
 EX
def area(radius):
temp = math.pi * radius**2
return temp
EX
def absolute_value(x):
if x < 0:
return -x
if x > 0:
return x ROHITA YAMAGANTI
2. void function:
 A function that doesn’t return a value.
void functions might display something on the screen or have some
other effect, but they don’t have a return value.

EX
def print_twice(bruce):
print(bruce)
print(bruce)
print_twice('Spam')

ROHITA YAMAGANTI
Function arguments:
we can call a function by using the following types of formal arguments:

 Required arguments
 Keyword arguments
 Default arguments
 Variable-length arguments

ROHITA YAMAGANTI
Required arguments:

 Required arguments are the arguments passed to a function in correct


positional order. Here, the number of arguments in the function call
should match exactly with the function definition.
Ex
def printme(str):
print(“Hello,”+str)
printme(“students”)

 To call the function printme(), you definitely need to pass one


argument, otherwise it would give a syntax error

ROHITA YAMAGANTI
Keyword arguments:

 Keyword arguments are related to the function calls.


 When you use keyword arguments in a function call, the caller
identifies the arguments by the parameter name.
 This allows you to skip arguments or place them out of order because
the Python interpreter is able to use the keywords provided to match
the values with parameters.
EX
def printme(name, msg=“Good Evening”):
print(“Hello,”+name+’ ’+msg)
printme(name=“students”, msg=“Good morning”)

ROHITA YAMAGANTI
Default arguments:
 A default argument is an argument that assumes a default value if a
value is not provided in the function call for that argument.

EX

def printme(name = “friend”, msg=“Good Evening”):


print(“Hello,”+name+’ ’+msg)
printme(name=“students”, msg=“Good morning”)

ROHITA YAMAGANTI
Variable-length arguments:
 You may need to process a function for more arguments than you
specified while defining the function.
 These arguments are called variable-length arguments and are not
named in the function definition, unlike required and default
arguments.

EX:
def greet(*names):
for name in names:
print(“Hello”,name)
greet(“Mounika”,”Luke”,”steve”,”John”)

ROHITA YAMAGANTI
Advantages of Recursion
1.Recursive functions make the code look clean and elegant.
2.A complex task can be broken down into simpler sub-problems using
recursion.
3.Sequence generation is easier with recursion than using some nested
iteration.
Disadvantages of Recursion
1.Sometimes the logic behind recursion is hard to follow through.
2.Recursive calls are expensive (inefficient) as they take up a lot of memory
and time.
3.Recursive functions are hard to debug.

ROHITA YAMAGANTI
Anonymous Functions:

A function which does not contain any name is known as a


lambda function or Anonymous function.

Syntax: lambda arguments: expression


Lambda function we can assign to the variable and we can call
the function through that variable.
syntax: ASSIGNED VARIABLE = lambda ARGUMENT : ACTION
x               = lambda            y     :    y*2
 
Ex myfun=lambda x:x*x
p=myfun(10)
print(p)

Output
ROHITA YAMAGANTI
100
ROHITA YAMAGANTI
filter():
The filter() function in Python takes in a function and a list as
arguments. It filter out all the elements of a sequence “sequence”, for
which the function returns True.
Ex my_list=[1,5,4,6,8,11,3,12]
new_list=list(filter(lambda x:(x%2==0),my_list))
print(new_list)
Output
[4,6,8,12]
map():
The map() function in Python takes in a function and a list as
argument. The function is called with a lambda function and a new
list is returned which contains all the lambda modified items
returned by that function for each item.
Ex my_list=[1,5,4,6,8,11,3,12]
new_list=list(map(lambda x:( x*x),my_list))
print(new_list)
Output [1,25,16,36,64,121,9,144]
ROHITA YAMAGANTI
ROHITA YAMAGANTI
reduce():

 The reduce() function in Python takes in a function and a list as


argument. The function is called with a lambda function and a list
and a new reduced result is returned.
 This performs a repetitive operation over the pairs of the list.
This is a part of functools module.

EX

from functools import reduce


li = [5, 8, 10, 20, 50, 100]
sum = reduce((lambda x, y: x + y), li)
print (sum)

ROHITA YAMAGANTI
ROHITA YAMAGANTI
Global Variables:

 A global variable is accessible to all the functions in a program file.


 When a variable is created by an assignment statement that is
written outside all the functions in a program file, the variable is
global.

EX
my_value = 10
def show_value():
print(my_value)
show_value()
Program Output
10

ROHITA YAMAGANTI
 In order to modify the global variables data with in the function
we should use global declaration with in the function.

EX: Output:
a=1000 1000
b=2000 2000
def f1(): 3000
global a 4000
global b
print(a)
print(b)
a=3000
b=4000
def f2():
print(a)
print(b)
f1()
f2() ROHITA YAMAGANTI
Local Variables:

 A local variable is created inside a function and cannot be


accessed by statements that are outside the function.
 Different functions can have local variables with the same names
because the functions cannot see each other’s local variables.

EX
def main():
get_name()
print('Hello', name) # This causes an error!
def get_name():
name = input('Enter your name: ')
main()

ROHITA YAMAGANTI
Mutable V/s Immutable Data Types :

Mutable Data Type Immutable Data Type

1. Sequences can be modified 1. Sequences cannot be


after creation modified after creation

2. Ex: Lists, Dictionary, Sets 2. Ex: Strings, Tuples

3. Operations like add, delete 3. Operations like add, delete


and update can be performed and update cannot be
performed

ROHITA YAMAGANTI
Strings:

 In Python, string is a sequence of Unicode character. Unicode was


introduced to include every character in all languages and bring
uniformity in encoding.

Create a string:

 Strings can be created by enclosing characters inside a single


quote ( ‘ ), double quotes ( “ ) and triple code ( “ “ “ )
 It must start and end with same type of quote
 Tripe quotes are used to span string across multiple lines
 Index starts from zero
 Can be accessed using negative indices. Last character will start
with
-1 and traverses from right to left
ROHITA YAMAGANTI
Syntax:
word = ‘Python Programming’
sentence = “ Object Oriented Programming”
paragraph =“ “ “ Python is a Object Oriented Programming
Language. It is a Biginners Language “”’

Example :
my_string = ‘Hello‘
print(my_string)
my_string1 = input("Enter a string")
print(my_string1)
my_string2 = """Hello, welcome to the world of Python"""
print(my_string2)

ROHITA YAMAGANTI
Access characters in a string:

 We can access individual characters using indexing and a range of


characters using slicing. Index starts from 0. Trying to access a
character out of index range will raise an Index Error.
 The index must be an integer. We can't use float or other types,
this will result into Type Error.
 Python also allows negative indexing for its sequences.

Example
str = 'program’ print('str = ', str)
#first character print('str[0] = ', str[0])
#last character print('str[-1] = ', str[-1])
#slicing 2nd to 5th character print('str[1:5] = ', str[1:5])

ROHITA YAMAGANTI
change or delete a string:

 Strings are immutable. This means that elements of a string can


not be changed once it has been assigned. We can simply
reassign different strings to the same name.
 We can not delete or remove characters from a string. But
deleting the string entirely is possible using the keyword del.

Example:
my_string = 'perl'
my_string = 'Python'
print my_string
del my_string
print (my_string)

ROHITA YAMAGANTI
Concatenation of Two or More Strings:

 Joining of two or more strings into a single one is called


concatenation. The + operator does this in Python.
 The * operator can be used to repeat the string for a given
number of times.

Example:
str1 = 'Hello’
str2 ='World!'
# using +
print('str1 + str2 = ', str1 + str2)
# using *
print('str1 * 3 =', str1 * 3)

ROHITA YAMAGANTI
String Formatting Operator:

1. One of Python's coolest features is the string format operator %.


2. This operator is unique to strings and makes up for the pack of
having functions from C's printf() family.
%s : string conversion via str() prior to formatting
%d : signed decimal integer
%f : floating point real number

Example:
print ("My name is %s and weight is %d kg!" % ('student', 45) )

Output:
My name is student and weight is 45 kg!

%d, %i, %o , %u , %x , %X , %e , %E , %f , %F , %g , %G , %c , %r ,
%s, %% ROHITA YAMAGANTI
Escape Sequence:
 If we want to print a text like –He said, "What‘s there?"-we can
neither use single quote or double quotes.
 This will result into Syntax Error as the text itself contains both
single and double quotes.
 One way to get a round this problem is to use triple quotes.
Alternatively, we can use escape sequences.
 An escape sequence starts with a backslash and is interpreted
differently.
 If we use single quote to represent a string, all the single quotes
inside the string must be escaped. Similar is the case with double
quotes
Example
# using triple quotes print('''He said, "What's there?"''')
# escaping single quotes print('He said, "What\'s there?"')
# escaping double quotes print("He said, \"What's there?\"")
ROHITA YAMAGANTI
String methods with example:

s="hello this is my class my "


print (s.capitalize()) # Copy of s with only the first character capitalized
print (s.title() ) # Copy of s first character of each word capitalized
print (s.upper()) # copy of s all characters converted to uppercase
print (s.lower() ) # Copy of s in all lowercase letters
print (s.center(50)) #Center s in a field of given width
print (s.ljust(10)) # Like center, but s is left-justified
print (s.rjust(30)) #Like center, but s is right-justified
Print(s.count('my')) #Count the number of occurrences of substring in s
print (s.find('my')) #Find the first position where sub occurs in s
print (s.rfind('my')) #Like find, but returns the right-most position(index)
ROHITA YAMAGANTI
print (s.replace('my', 'one')) #Replace occurrences of oldsub in s with
new sub
list1= s.split() #Split s into a list of substrings
print (list1)
sub="“
string=sub.join(list1) # Concatenate list of strings into one
large print string using s as separator.

ROHITA YAMAGANTI
String Operations and Functions:
Concatenation :
-Strings can be concatenated with “+ “ operator
“Hello” + “World” will result in HelloWorld
Repetition :
-Repeated concatenation of string can be done using asterisk operator “
*“
“Hello” * 3 will result in “HelloHelloHello”
Indexing:
-“Python” [0] will result in “P”
Slicing:
-Substrings are created using two indices in a square bracket separated
by a “ :”
-“Python”[2:4]will result in “th”
Size
-prints: length of string
len(“python”) will result in 6
ROHITA YAMAGANTI
Escape Characters:
 Following table is a list of escape or non-printable characters that
can be represented With backslash notation.
 An escape character gets interpreted; in a single quoted as well as
double quoted strings.
Escape character Meaning
\a Bell or Alert
\b Backspace
\n New Line
\t Horizontal tab space
\v Vertical tab space
\r Enter button
\x Character X
\\ Display single \

ROHITA YAMAGANTI
String Formatting Operator:

ROHITA YAMAGANTI
ROHITA YAMAGANTI
List:
 Creating a list is as simple as putting different comma-separated
values between square brackets
 Important thing about a list is that items in a list need not be of the
same type
 An ordered group of sequences enclosed inside square brackets and
separated by symbol ,
 List are mutable type,Python will not create a new list if we modify
an element in the list.
Syntax:

list1= [ ] # Creation of empty List


list2= [ Sequence1, ] # In this case symbol , is not mandatory
list3= [ Sequence1, Sequence2]
Ex: language=[“Python”]
languages =[“Python”, “C”,”C++”,”Java”, ”Perl”, ”R”]
ROHITA YAMAGANTI
A list can be composed by storing a sequence of different type of values
separated by commas.
The elements are stored in the index basis with starting index as 0.

Ex:

data1=[1,2,3,4]
data2=['x','y','z']
data3=[12.5,11.6]
data4=['raman','rahul']
data5=[]
data6=['abhinav',10,56.4,'a']

ROHITA YAMAGANTI
Accessing Values in Lists
A list can be created by putting the value inside the square bracket and
separated by comma.
Syntax:
<list_name>=[value1,value2,value3,...,value n]
For accessing list :
<list_name>[index]
list1 = ['physics', 'chemistry', 1997, 2000]
list2 = [1, 2, 3, 4, 5, 6, 7 ]
print ("list1[0]: ", list1[0])
print ("list2[1:5]: ", list2[1:5])
print (“list1[0:] : “, list1[0:])
Output
list1[0]: physics
list2[1:5]: [2, 3, 4, 5]
list1[0:] : ['physics', 'chemistry', 1997, 2000]
ROHITA YAMAGANTI
Elements in a Lists:
Data=[1,2,3,4,5];
Data[0]=1=Data[-5],
Data[1]=2=Data[-4],
Data[2]=3=Data[-3],
Data[3]=4=Data[-2],
Data[4]=5=Data[-1].

Note: Internal Memory Organization:


List do not store the elements directly at the index. In fact a
reference is stored at each index which subsequently refers to the
object stored somewhere in the memory. This is due to the fact that
some objects may be large enough than other objects and hence they
are stored at some other memory location.

ROHITA YAMAGANTI
List operations
Adding Lists : The + operator concatenates lists:
a = [1, 2, 3] # list1
b = [4, 5, 6] # list2
c = a + b # list3
print c
Output : [1,2, 3, 4, 5, 6]
Replicating lists: Similarly, the * operator repeats a list a given
number of times:
a= [7, 8, 9]
b=a*3
print b
Output [7, 8, 9, 7, 8, 9, 7, 8, 9]
Note: '+'operator implies that both the operands passed must be list
else error
list1=[10,20]
list1+30
print list1 # error ROHITA YAMAGANTI
List membership:

in and not in are Boolean operators that test membership in a


sequence.
Example
list1=[1,2,3,4,5,6]
print 5 in list1

Output
True

list1=[1,2,3,4,5,6]
print -5 in list1
Output
False
ROHITA YAMAGANTI
List slicing:

A subpart of a list can be retrieved on the basis of index. This


subpart is known as list slice.
Example:
fruits=["bana","orange","apple","kiwi"]
print (fruits[1:3])
print (fruits[:3])
print (fruits[:])
Output
['orange', 'apple']
['bana', 'orange', 'apple']
['bana', 'orange', 'apple', 'kiwi']

Note: If the index provided in the list slice is outside the list, then it
raises an IndexErrorexception
ROHITA YAMAGANTI
Other Operations:

Apart from above operations various other functions can also be


performed on List such as Updating, Appending and Deleting
elements from a List:

a) Updating elements in a List:

To update or change the value of particular index of a list, assign the


value to that particular index of the List.
Syntax:

<list_name>[index]=<value>

ROHITA YAMAGANTI
Updating Lists
list = ['physics', 'chemistry', 1997, 2000];
print ("Value available at index 2 : “,print list[2])
list[2] = 2001;
print ("New value available at index 2 : “,print list[2])

Output
Value available at index 2 : 1997
New value available at index 2 : 2001

ROHITA YAMAGANTI
Appending elements to a List:

append() method is used to append i.e., add an element at the end


of the existing elements.
Syntax: <list_name>.append(item)
Eg: list1=[10,"rahul",'z']
print ("Elements of List are:”)
print (list1)
list1.append(10.45)
print("List after appending:“)
Print (list1)

Output:
Elements of List are:[10,'rahul','z']
List after appending:[10,'rahul','z',10.45]
ROHITA YAMAGANTI
Delete List Elements:

del statement can be used to delete an element from the list. It can
also be used to delete all items from start Index to end Index.

Example:

list1 = ['physics', 'chemistry', 1997, 2000];


print (list1)
del (list1[2])
print ("After deleting value at index 2 : “)
Print( list1)

Output
['physics', 'chemistry', 1997, 2000]
After deleting value at index 2 :['physics', 'chemistry', 2000
ROHITA YAMAGANTI
Functions and Methods of Lists:
There are many Built-in functions and methods for Lists. They are as
follows:

There are following List functions:


Function Description
min(list) Returns the minimum value from the list given.
max(list) Returns the largest value from the given list.
len(list) Returns number of elements in a list.
cmp(list1,list2) Compares the two list.
list(sequence) Takes sequence types and converts them to
lists.
ROHITA YAMAGANTI
min(list):
The method min() returns the elements from the list with minimum
value.
Syntax
min(list)
Example
List1=[80,100,1000]
print ("min(80, 100, 1000) : ", min(List1))
Lst_string=['a', 'zx', 'y']
print ("min['a', 'zx', 'y'] : ", min(Lst_string))
Output:
min[80,100,1000] : 80
min['a', 'zx', 'y'] : 'a'

ROHITA YAMAGANTI
max(list)
The method max returns the elements from the list with maximum
value.
Syntax
max(list)
Example
List1=[80,100,1000]
print ("max(80, 100, 1000) : ", max(List1))
Lst_string=['a', 'zx', 'y']
print ("max['a', 'zx', 'y'] : ",max( Lst_string))
Output:
max[80,100,1000] : 1000
max['a', 'zx', 'y'] : 'zx'

ROHITA YAMAGANTI
Built-in List Functions

len(list)
The method len( ) returns the number of elements in the list.
Syntax
len(list)
Example
list1, list2 = [123, 'xyz', 'zara'], [456, 'abc']
print ("First list length : ", len(list1))
print ("Second list length : ", len(list2))
Output
First list length : 3
Second list length :2

ROHITA YAMAGANTI
cmp(list1,list2):
Explanation: If elements are of the same type, perform the
comparison and return the result. If elements are different types,
check whether they are numbers.
If numbers, perform comparison.
If either element is a number, then the other element is returned.
Otherwise, types are sorted alphabetically .

If we reached the end of one of the lists, the longer list is "larger." If
both list are same it returns 0.
Eg:
list1=[101,981,'abcd','xyz','m']
list2=['aman','shekhar',100.45,98.2]
list3=[101,981,'abcd','xyz','m']
printcmp(list1,list2)
printcmp(list2,list1)
printcmp(list3,list1)
ROHITA YAMAGANTI
list(seq):

The method list() takes sequence types and converts them to lists.
This is used to convert a given tuple into list.

Note: Tuple are very similar to lists with only difference that element
values of a tuple can not be changed and tuple elements are put
between parentheses instead of square bracket.
Syntax
list(seq)

ROHITA YAMAGANTI
There are following built-in methods of List:

Methods Description
index(object) Returns the index value of the object.
count(object) It returns the number of times an object is repeatedin
list.
pop()/pop(index) Returns the last object or the specified indexed object.
It removes the popped object.
insert(index,object) Insert an object at the given index.
extend(sequence) It adds the sequence to existing list.
remove(object) It removes the object from the given List.
reverse() Reverse the position of all the elements of a list.
sort() It is used to sort the elements of the List.
Example
aTuple= (123, 'xyz', 'zara', 'abc')
aList= list(aTuple)
print ("List elements : ", aList)
Output
List elements : [123, 'xyz', 'zara', 'abc']
ROHITA YAMAGANTI
Built-in List Methods
append()
The method append() appends a passed objinto the existing list.
Syntax
list.append(obj)
Example
aList= [123, 'xyz', 'zara', 'abc']
aList.append( 2009 );
print ("Updated List : ", aList)
Output:
Updated List : [123, 'xyz', 'zara', 'abc', 2009]
count()
The method count() returns count of how many times obj occurs in
list.
Syntax
list.count(obj)
ROHITA YAMAGANTI
Example
Li= [123, 'xyz', 'zara', 'abc', 123]
print( "Count for 123 : ", Li.count(123))
print( "Count for zara: ", Li.count('zara'))
Output
Count for 123 : 2
Count for zara: 18/1
extend()
The method extend() appends the contents of seq to list.
Syntax
list.extend(seq)
Example
l1= [123, 'xyz', 'zara', 'abc', 123]
l2= [2009, 'manni']
l1.extend(l2)
print( "Extended List : ", l1)
Output
Extended List : [123, 'xyz', 'zara', 'abc', 123, 2009, 'manni']
ROHITA YAMAGANTI
index()
The method index() returns the lowest index in list that obj appears.
Syntax
list.index(obj)
Example
aList= [123, 'xyz', 'zara', 'abc']
print ("Index for xyz : ", aList.index( 'xyz' ) )
print ("Index for zara: ", aList.index( 'zara' ))
Output
Index for xyz : 1
Index for zara: 2
insert()
The method insert() inserts object objinto list at offset index.
Syntax
list.insert(index, obj) Output:
Example: li= [123,'xyz','zara','abc']
li.insert( 3, 2009) Final List : [123, 'xyz',
print("Final List:",li) 'zara', 2009,
ROHITA YAMAGANTI
'abc']
pop() The method pop() removes and returns last object or obj from
the list.
Syntax: list.pop(obj=list[-1])
Example aList= [123, 'xyz', 'zara', 'abc'] Output
print ("A List : ", aList.pop()) A List : abcB
print ("B List : ", aList.pop(2) ) List : zara8/1
remove()
This is the object to be removed from the list.
This method does not return any value but removes the given object
from the list.
Syntax
list.remove(obj)
Example aList= [123, 'xyz', 'zara', 'abc', 'xyz']
aList.remove('xyz') Output
print ("List : ", aList) List : [123, 'zara', 'abc', 'xyz']
aList.remove('abc') List : [123, 'zara', 'xyz']
print ("List : ", aList)
ROHITA YAMAGANTI
reverse()
The method reverse() reverses objects of list in place.
This method does not return any value but reverse the given object
from the list.
Syntax
list.reverse()
Example aList= [123, 'xyz', 'zara', 'abc', 'xyz'] Output
aList.reverse() List : ['xyz', 'abc', 'zara', 'xyz',
print ("List : ", aList) 123]
sort()
The method sort() sorts objects of list, use compare func if given.
This method does not return any value but reverse the given object
from the list.
Syntax
list.sort([func])
Example aList= [123, 'xyz', 'zara', 'abc', 'xyz'] Output
aList.sort() List : [123, 'abc', 'xyz', 'xyz', 'zara']
print ("List : ",ROHITA
aList)
YAMAGANTI
Aliasing
Since variables refer to objects, if we assign one variable to another,
both variables refer to the same object
Example a=[1,2,3]
b=a
if a is b:
print "True“
else:
print "False“
Output
True
In this case, the state snapshot looks like this:
a-------[1,2,3]
b-------[1,2,3]
Because the same list has two different names, a and b , we say that it
is aliased. Changes made with one alias affect the other
ROHITA YAMAGANTI
Cloning
If we want to modify a list and also keep a copy of the original, we
need to be able to make a copy of the list itself, not just the
reference. This process is sometimes called cloning, to avoid the
ambiguity of the word copy.
The easiest way to clone a list is to use the slice operator:
a=[1,2,3]
b=a[:]
print (b)
print (a)
b[0]=5
print (b)
print (a)
Output
[1, 2, 3]
[1, 2, 3]
[5, 2, 3]
[1, 2, 3] ROHITA YAMAGANTI
for loop Syntax Or VARIABLE in LIST: BODY

Note: Each time through the loop, the variable I is used as an index
into the list, printing the i’th element. This pattern of computation
is called a list traversal.
Example 1
friends = ["ram", "laxman", "Bharat", "janaki"]
for friend in friends:
print friend
Output
ram
laxman
Bharat
janaki

ROHITA YAMAGANTI
Example 2
xs= [1, 2, 3, 4, 5]
for (i, val) in enumerate(xs):xs[i] = val**2
print (xs[i]) Output: 1491625
List parameters
Passing a list as an argument actually passes a reference to the list,
not a copy or clone of the list. So parameter passing creates an alias
for you:the caller has one variable referencing the list, and the called
function has an alias, but there is only one underlying list object.
Functions that produce lists
def double_stuff(a_list):
for (i, val) in enumerate(a_list):a_list[i] = val*2
return a_list[i]
xs= [ 2, 3, 4, 5]
print double_stuff(xs)
Output
[4, 6, 8, 10]
ROHITA YAMAGANTI
Strings and lists
An optional argument called a delimiter can be used to specify
which string to use as the boundary marker between substrings. The
following example uses the string in as the delimiter:
Example
s="The rain in india“
w=s.split("in")
print w
Output['The ra', ' ', ' ', 'dia']
The inverse of the split method is join . You choose a desired
separator string, (often called the glue ) and join the list with the
glue between each of the elements:
Example
w="The rain in india“
glue=";“
s=glue.join(w)
print s
Output : T;h;e; ;r;a;i;n; ;i;n; ;i;n;d;i;a]
ROHITA YAMAGANTI
Nested lists
A nested list is a list that appears as an element in another list. In this
list, the element with index 3 is a nested list:
Example
nested = ["hello", 2.0, 5, [10, 20]]
print(nested[3])
Output [10, 20]
Nested lists
To extract an element from the nested list, we can proceed in two
steps:
Example
nested = ["hello", 2.0, 5, [10, 20]]
print(nested[3][0]) Output 10
Matrices
Nested lists are often used to represent matrices. For example, the matrix:
mx= [[1, 2, 3], [4, 5, 6], [7, 8, 9]]mxis a list with three elements, where each
element is a row of the matrix. We can select an entirerow from the matrix
in the usual way:>>> mx[1][4, 5, 6]
ROHITA YAMAGANTI
difference between append() and extend()

The method appendadds its parameter as a single element to the


list, while extendgets a list and adds its content.
Example

first = [10,20,30]
second = [40,50,60]
first.append([70,80,90])
second.extend([100,110,120])
print first
print second

Output [10, 20, 30, [70, 80, 90]][40, 50, 60, 100, 110, 120]

ROHITA YAMAGANTI
Searching listsdata = [['a','b'], ['a','c'], ['b','d']]
search = 'c'
for i in data:
if i[1] == search:
print "Found it!",i
break
Output: Found it! ['a', 'c']

ROHITA YAMAGANTI
Tuples
 An ordered group of sequence seperated by symbol, and enclosed
inside the parenthesis
 A tuple is a sequence of immutable objects, therefore tuple can
not be changed
 In Python, tuple is similar to a list.Only the difference is that list
is enclosed between square bracket,tuple between parenthesis and
List have mutable objects where asTuple have immutable objects.
NOTE:If Parenthesis is not given witha sequence,itis by default
treated as Tuple.
AdvantagesofTupleoverList
 Since tuple are immutable, iterating through tuple is faster than
with list. So there is a slight performance boost.
 It makes the data safe as tuples are immutable and hence can not
be changed.
 Tuples that contain immutable elements can be used as key for a
dictionary. With list, this is not possible.
 Tuples are used for String formatting.
ROHITA YAMAGANTI
CreatingaTuple
A tuple is created by placing all the items (elements) inside a
parentheses(), separated by comma.
The parentheses are optional but is a good practice to write it.
A tuple can have any number of items and they may be of different
types(integer, float, list,stringetc.).
Syntax:tuple1=() #creationofemptytuple
tuple2=(Sequence1,)#,symbol is mandatory with out which it
becomes just a string assignment operator
tuple3=(Sequence1,Sequence2)

Example

my_tuple=(1,3.2,"mouse",[8,4,6],(1,2,3))
print(my_tuple)

ROHITA YAMAGANTI
Tuples can also be nested.
Ex-
tupl1='a','mahesh',10.56
tupl2=tupl1,(10,20,30)
print (tupl1)
print (tupl2)
Output:
>>>('a','mahesh',10.56)

(('a','mahesh',10.56),(10,20,30))

ROHITA YAMAGANTI
Accessing Elements in a Tuple
 We can use the index operator[] to access an item in a tuple where
the index starts from 0. So, a tuple having 6 elements will have index
from 0 to 5.Trying to access an element other that(6,7,...)will raise an
Index Error.
 The index must be an integer, so we can not use float or other
types. This will result into Type Error. Likewise ,nested tuple are
accessed using nested indexing as shown in the example below.
 Python allows negative indexing for its sequences.
Example
n_tuple = (1,"mouse", [8, 4, 6], (1, 2, 3))
# Output: 's‘ print(n_tuple[1][3])
# Output: 4 print(n_tuple[2][1])
# Output: 1 print(n_tuple[0])
# Output: [8, 4, 6] print(n_tuple[-2])

ROHITA YAMAGANTI
Tuple Operations : Slicing
 We can access arange of items in a tuple by using the slicing
operator-colon":".
 A sub part of a tuple can be retrieved on the basis of index. This
subpart is known as tuple slice.
 If the index provided in the Tuple slice is outside the list, then it
raises an Index Error exception
Example
my_tuple = ('p','r','o','g','r','a','m')
# Output: ('r', 'o', 'g')print(my_tuple[1:4])
# Output: ('p', 'r')print(my_tuple[:-5])
# Output: ('a', 'm')print(my_tuple[5:])
# Output: ('p', 'r', 'o', 'g', 'r', 'a', 'm')print(my_tuple[:])
# Output: (‘m’)print(my_tuple[-1])
# Output: ('p','r','o','g','r','a','m')print(my_tuple)
ROHITA YAMAGANTI
Changing a Tuple
 Unlike lists, tuples are immutable. This means that elements of a
tuple can not be changed once it has been assigned. But, if the
element is itself a mutable datatype like list,its nested items can be
changed. We can also assign a tuple to different
values(reassignment).
Example
my_tuple = (4, 2, 3, [6, 5])
my_tuple[3][0] = 9
print(my_tuple)#(4, 2, 3, [9, 5])
my_tuple[1]=40
#TypeError: 'tuple' object does not support item assignment
print(my_tuple)

ROHITA YAMAGANTI
 We can use + operator to combine two tuples. This is also called
concatenation.
 We can also repeat the elements in a tuple for a given
number of times using the * operator.
 Both + and * operations result into a new tuple.
Example
# Concatenation
# Output: (1, 2, 3, 4, 5, 6)print((1, 2, 3) + (4, 5, 6))
# Repeat
# Output: ('Repeat', 'Repeat', 'Repeat')print(("Repeat",) * 3)

ROHITA YAMAGANTI
Deleting a Tuple
 we cannot delete or remove items or elements from a tuple.
 But deleting a tuple entirely is possible using the keyword del.
Example
my_tuple = ('p','r','o','g','r','a','m')
del my_tuple # will delete the tuple data
print(my_tuple) # will show an error sice tuple data is already
deleted
Tuple Methods
 Methods that add items or remove items are not available with
tuple. Only the following two methods are available.
 count(x) Return the number of items that is equal to x
 index(x) Return index of first item that is equal to x
Example
my_tuple = ('a','p','p','l','e',)
print(my_tuple.count('p'))#Output:2
print(my_tuple.index('l'))#Output:3
ROHITA YAMAGANTI
Tuple functions
 all ( T) -Return True if all elements of the tuple are true (or if the
tuple is empty).
 any( T) -Return True if any element of the tuple is true. If the
tuple is empty, return False.
 enumerate( T) -Return an enumerate object. It contains the index
and value of all the items of tuple as pairs.
 len( T) -Return the length (the number of items) in the tuple.
 max(T ) -Return the largest item in the tuple.
 min( T) -Return the smallest item in the tuple
 sorted(T ) -Take elements in the tuple and return a new sorted list
(does not sort the tuple itself).
 sum( T) -Retrun the sum of all elements in the tuple.
 tuple( T) -Convert an inerrable (list, string, set, dictionary) to a
tuple.
 cmp( t1,t2) –To compare the two given tuples
 tuple(sequence) –Converts the sequence into tuple
ROHITA YAMAGANTI
cmp(tuple1,tuple2)
Explanation: If elements are of the same type, perform the
comparison and return the result. If elements are different types,
check whether they are numbers
 If numbers, perform comparison.
 If either element is a number, then the other element is returned.
 Otherwise, types are sorted alphabetically.
 If we reached the end of one of the lists, the longer list is "larger.“
If both list are same it returns 0.
Eg:
data1=(10,20,'rahul',40.6,'z')
data2=(20,30,'sachin',50.2) Output:
-1
print cmp(data1,data2)
print cmp(data2,data1) 1
data3=(20,30,'sachin',50.2) 0
printcmp(data2,data3)

ROHITA YAMAGANTI
Example
pyTuple =(20,55,43,22,67,90,0) # data=(10,20,‘Ravi',40.6,'z')
print all(pyTuple)Try out
print any(pyTuple)
print len(pyTuple)
print max(pyTuple)
print min(pyTuple)
print sum(pyTuple)
print sorted(pyTuple)
a=enumerate(pyTuple)
print tuple(a)
for item in enumerate(pyTuple):
print(item)

ROHITA YAMAGANTI
Dictionaries:

 Python dictionary is an unordered collection of items


 Dictionaries are mutable i.e., it is possible to add, modify and
delete key-value pairs
 Keys are used instead of indexes
 Keys are used to access elements in dictionary and keys can be of
type- strings, number, list etc
 A list of elements with key and value pairs (seperated by symbol:)
inside curly braces
 The key must be unique [Immutable], separated by colon(:) and
enclosed with curly braces

ROHITA YAMAGANTI
 While other compound data types have only value as an element,
a dictionary has a set of key & value pair known as item.
 Creating a dictionary is as simple as placing items inside curly
braces{} separated by comma.
 We can also create a dictionary using the built-in function dict()
 Dictionary is known as Associative Array

Ex:
plant={} #we can have our own index
plant[1]="Rose"
plant[2]="Lotus"
plant["name"]="Jasmin"
plant["color"]="Green"
print(plant)

ROHITA YAMAGANTI
Examples:8/4/2017
# creation of empty dictionary my_dict= {}
# dictionary with integer keys my_dict= {1: 'apple', 2: 'ball'}
# dictionary with mixed keys my_dict= {'name': 'John', 1: [2,
4, 3]}
# using dict( ) my_dict= dict({1:'apple',
2:'ball'})
# from sequence having each item as a pair
my_dict= dict([(1,'apple'), (2,'ball')])
phonebook={}
#creation of empty Dictionary
phonebook={“Ravi”:9247448766}
#Dict.withKVpair
phonebook={“Ravi”:9247448766,”Rahul”:9985933931}
#Dict. With 2 K-VPairs

ROHITA YAMAGANTI
Accessing Elements in a Dictionary
 While indexing is used with other container types to access values,
dictionary uses keys.
 Key can be used either inside square brackets or with the get()
method.
 The difference while using get() is that it returns None instead of
Key Error, if the key is not found.
Example Output
my_dict= {'name':'student', 'age': 26} student
print (my_dict['name']) 26
print (my_dict.get('age')) None
print (my_dict.get('address')) KeyError: 'address'
print (my_dict['address'])
Changing or Adding Elements in a Dictionary
 Dictionaries are mutable. We can add new items or change the
value of existing items using assignment operator.
 If the key is already present, value gets updated, else a new key:
value pair is added to the dictionary.
ROHITA YAMAGANTI
Example
 my_dict={'age': 26, 'name': ‘siri'}
 my_dict['age'] = 27 # update value
 print(my_dict)
 my_dict['address'] = 'Downtown' # add item
 print(my_dict)

Output

{'age': 27, 'name': ‘siri'}


{'age': 27, 'name': ‘siri', 'address': 'Downtown'}

ROHITA YAMAGANTI
Deleting or Removing Elements from a Dictionary:

 We can remove a particular item in a dictionary by using the


method pop().
 This method removes as item with the provided key and returns
the value.
 The method, popitem() can be used to remove and return an
arbitrary item(key,value ) form the dictionary.
 All the items can be removed at once using the clear() method.
 We can also use the del keyword to remove individual items or
the entire dictionary itself.

ROHITA YAMAGANTI
Example
squares = {1:1, 2:4, 3:9, 4:16, 5:25} # create a dictionary
print(squares.pop(4)) # remove a particular item
print(squares)
Output:16
{1: 1, 2: 4, 3: 9, 5: 25}
squares = {1:1, 2:4, 3:9, 4:16, 5:25} # create a dictionary
print(squares.popitem()) # remove an arbitrary item
Output:(5, 25)
squares = {1:1, 2:4, 3:9, 4:16, 5:25} # create a dictionary
del(squares[5]) # delete a particular item
print(squares)
Output:{1: 1, 2: 4, 3: 9, 4: 16}
squares = {1:1, 2:4, 3:9, 4:16, 5:25} # create a dictionary
squares.clear() # remove all items
print(squares)
Output:{}
ROHITA YAMAGANTI
Dictionary Comprehension
 Dictionary comprehension is an elegant and concise way to
create new dictionary from an iterable in Python.
 Dictionary comprehension consists of an expression
pair(key:value) followed by for statement inside curly braces{}.
 Here is an example to make a dictionary with each item being a
pair of a number and its square.
Example
squares = {x: x*x for x in range(6)}
print (squares)
Output: {0: 0, 1: 1, 2: 4, 3: 9, 4: 16, 5: 25}
#This code is equivalent to
squares = {}
for x in range(6):
squares[x] = x*x
print squares
Output:{0: 0, 1: 1, 2: 4, 3: 9, 4: 16, 5: 25}
ROHITA YAMAGANTI
Dictionary Comprehension
 A dictionary comprehension can optionally contain more for or if
statements.
 An optional if statement can filter out items to form the new
dictionary. Here are some examples to make dictionary with only
odd items.
Example odd_squares={x:x*x for x in range(11) if x%2==1}
print(odd_squares)
Output: {1:1,3:9,5:25,7:49,9:81}
Dictionary Membership Test
 We can test if a key is in a dictionary or not using the keyword in.
Notice that membership test is for keys only, not for values.
Example squares={1:1,3:9,5:25,7:49,9:81}
print(1 in squares)
print(2 not in squares)
#membership tests for key only not value
print(49 in squares)
Output TrueTrueFalse ROHITA YAMAGANTI
Iterating Through a DictionaryUsing a for loop
we can iterate though each key in a dictionary.
Example: squares={1: 1, 3: 9, 5: 25, 7: 49, 9: 81}
for i in squares:
print(squares[i])
Output: 19254981
Built-in Functions with Dictionary
 all() Return True if all keys of the dictionary are true(or if the
dictionary is empty).
 any() Return True if any key of the dictionary is true. If the
dictionary is empty, return False.
 len() Return the length (the number of items) in the dictionary.
 cmp(d1,d2) Compares items of two dictionaries.
 sorted() Return a new sorted list of keys in the dictionary.
any( ) & all( )
• any(l == 't' for l in 'python') # Returns True. Same as: 't' in 'python’
• all(l == 't' for l in 'python') # Returns False. Not all of the letters are
't'.
ROHITA YAMAGANTI
Ex:square={0: 0, 0: 9, 0: 7, 0: 12}
squares={1: 1, 3: 9, 5: 25, 7: 49}
print len(squares)
print sorted(squares)
print cmp(squares,square)
Output: 4
[1, 3, 5, 7]
1
Ex:
squares={}
print all(squares)
print any(squares)
Output:
True
False

ROHITA YAMAGANTI
Dictionary Methods
str( ) Method
 The method str() produces a printable string representation of a
dictionary.
Syntax: str(dict)
Example
dict= {'Name': 'Zara', 'Age': 7}
print ("Equivalent String : %s" % str(dict))
Output
Equivalent String : {'Name': 'Zara', 'Age': 7}
copy() Method
 The method copy() returns a shallow copy of the dictionary.
Syntax: dict.copy()
Example
dict1 = {'Name': 'Zara', 'Age': 7}
dict2 = dict1.copy()
print ("New Dictinary: %s" % str(dict2))
Output New Dictinary: {'Age': 7, 'Name': 'Zara'}
ROHITA YAMAGANTI
fromkeys( ) Method
 The method fromkeys( ) creates a new dictionary with keys from
seqand values set to value.
 If we dontspecify a value in Dict. it assumes as keyword None
Syntax: dict.fromkeys(seq[, value]))
Example
seq= ('name', 'age', 'sex')
dict= dict.fromkeys(seq)
print ("New Dictionary : %s" % str(dict))
dict= dict.fromkeys(seq, 10)
print ("New Dictionary : %s" % str(dict))
Output
New Dictionary : {'age': None, 'name': None, 'sex': None}
New Dictionary : {'age': 10, 'name': 10, 'sex': 10}

ROHITA YAMAGANTI
has_key( ) Method
The method has_key() returns true if a given key is available in the
dictionary, otherwise it returns a false.
Syntax:
dict.has_key(key)
Example
dict= {'Name': 'Zara', 'Age': 7}
print "Value : %s" % dict.has_key('Age')
print "Value : %s" % dict.has_key('Sex')
Output
Value : True
Value : False

ROHITA YAMAGANTI
items() Method
The method items() returns a list of dict's(key, value) tuple pairs
Syntax: dict.items()
Example
dict= {'Name': 'Zara', 'Age': 7}
print "Value : %s" % dict.items()
Output Value : [('Age', 7), ('Name', 'Zara')]
setdefault() Method
The method setdefault() is similar to get(), but will set
dict[key]=default if key is not already in dict.
Syntax:
dict.setdefault(key, default=None)
Example: dict= {'Name': 'Zara', 'Age': 7}
print "Value : %s" % dict.setdefault('Age', None)
print "Value : %s" % dict.setdefault('Sex', None)
Output Value : 7
Value : None
ROHITA YAMAGANTI
update( ) Method
The method update() adds dictionary dict2's key-values pairs in to
dict. This function does not return anything.
Syntax: dict.update(dict2)
Example
dict= {'Name': 'Zara', 'Age': 7}
dict2 = {'Sex': 'female' }
dict.update(dict2)
print ("Value : %s" % dict)
Output
Value : {'Age': 7, 'Name': 'Zara', 'Sex': 'female'}
values( ) Method
The method values() returns a list of all the values available in a
given dictionary.
Syntax: dict.values()
Example dict= {'Name': 'Zara', 'Age': 7}
print "Value : %s" % dict.values()
Output ValueROHITA
: [7,YAMAGANTI
'Zara']

You might also like