0% found this document useful (0 votes)
13 views42 pages

Python Unit2

Uploaded by

rajputdhruv385
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
13 views42 pages

Python Unit2

Uploaded by

rajputdhruv385
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 42

UNIT- 2

Python Arrays
An array is a collection of items stored at contiguous memory locations. The idea is to store multiple
items of the same type together. This makes it easier to calculate the position of each element by
simply adding an offset to a base value, i.e., the memory location of the first element of the array
(generally denoted by the name of the array).

Array can be handled in Python by a module named array. They can be useful when we have to
manipulate only a specific data type values. A user can treat lists as arrays. However, user cannot
constraint the type of elements stored in a list. If you create arrays using the array module, all elements
of the array must be of the same type.

Creating array (Importing array module )

Array in Python can be created by importing array module.

array(data_type, value_list) is used to create an array with data type and value list specified in its
arguments.

Some of the data types are mentioned below which will help in creating an array of different data
types.
PYHTON PROGRAMMING

# Python program to demonstrate

# Creation of Array

# importing "array" for array creations import


array as arr

# creating an array with integer type

a = arr.array('i', [1, 2, 3])

# printing original array print ("The new


created array is : ", end =" ") for i in range (0,
3): print (a[i], end =" ") print()

# creating an array with float type

b = arr.array('d', [2.5, 3.2, 3.3])

# printing original array

print ("The new created array is : ", end =" ") for
i in range (0, 3):

print (b[i], end =" ")


PYHTON PROGRAMMING

Output :
The new created array is : 1 2 3

The new created array is : 2.5 3.2 3.3

Example import array as


arr a = arr.array('i', [2, 4,
6, 8])

print("First element:", a[0]) print("Second


element:", a[1])

print("Last element:", a[-1])

output

First element: 2
Second element: 4
Last element: 8

Comparison between Lists and Array in Python

Python List

A list is a mutable and ordered collection i.e., elements of the list can be changed and it maintains
the order of insertion of its items. Because of the property of order maintaining, each element of the
list has a fixed index and it permits the list to have duplicate elements. In Python, list is very useful as
it has the ability to contain non-homogeneous elements.

Python Array

Python arrays are also a collection but its items are stored at contiguous memory locations. It can
store only homogeneous elements(elements of the same data type). Arrays are very beneficial in
performing mathematical operations on the elements. Unlike lists, arrays can not be declared
directly. To create an array the array module must be imported and the syntax of the declaration is
different from that of the list.
PYHTON PROGRAMMING

Looping an array

import array as arr

# array with int type


a = arr.array('i', [1, 2, 3])

for i in (a):
print (i, end ="
") print()

output
123
Adding Elements to a Array
Elements can be added to the Array by using built-in insert() function. Insert is used to insert one or
more data elements into an array. Based on the requirement, a new element can be added at the
beginning, end, or any given index of array. append() is also used to add the value mentioned in its
arguments at the end of the array.

# Python program to demonstrate

# Adding Elements to a Array

# importing "array" for array creations import


array as arr

# array with int type

a = arr.array('i', [1, 2, 3])

print ("Array before insertion : ", end =" ")


for i in range (0, 3): print (a[i], end =" ")
print()

# inserting array
using # insert()
function a.insert(1,
4)
PYHTON PROGRAMMING

print ("Array after insertion : ", end =" ")


for i in (a): print (i, end =" ") print()

# array with float type b =


arr.array('d', [2.5, 3.2, 3.3])

print ("Array before insertion : ", end =" ")


for i in range (0, 3): print (b[i], end =" ")
print()

# adding an element using append() b.append(4.4)

print ("Array after insertion : ", end =" ")


for i in (b): print (i, end =" ") print()

Output :
Array before insertion : 1 2 3

Array after insertion : 1 4 2 3

Array before insertion : 2.5 3.2 3.3

Array after insertion : 2.5 3.2 3.3 4.4

Accessing elements from the Array


In order to access the array items refer to the index number. Use the index operator [ ] to access an
item in a array. The index must be an integer.

# Python program to demonstrate

# accessing of element from list

# importing array module

import array as arr

# array with int type

a = arr.array('i', [1, 2, 3, 4, 5, 6])

# accessing element of array


PYHTON PROGRAMMING

print("Access element is: ", a[0])

# accessing element of array print("Access


element is: ", a[3]) # array with float type
b = arr.array('d', [2.5, 3.2, 3.3])

# accessing element of array

print("Access element is: ", b[1])

# accessing element of array print("Access


element is: ", b[2])

Output :
Access element is: 1

Access element is: 4

Access element is: 3.2

Access element is: 3.3

Removing Elements from the Array


Elements can be removed from the array by using built-in remove() function but an Error arises if
element doesn’t exist in the set. Remove() method only removes one element at a time, to remove
range of elements, iterator is used. pop() function can also be used to remove and return an element
from the array, but by default it removes only the last element of the array, to remove element from
a specific position of the array, index of the element is passed as an argument to the pop() method.

Note – Remove method in List will only remove the first occurrence of the searched element.

# Python program to demonstrate

# Removal of elements in a Array

# importing "array" for array operations import


array

# initializing array with array values #


initializes array with signed integers

arr = array.array('i', [1, 2, 3, 1, 5])


PYHTON PROGRAMMING

# printing original array print ("The new


created array is : ", end ="") for i in range (0,
5):

print (arr[i], end =" ")

print ("\r")

# using pop() to remove element at 2nd position


print ("The popped element is : ", end ="") print
(arr.pop(2))

# printing array after popping print ("The


array after popping is : ", end ="") for i in
range (0, 4):

print (arr[i], end =" ")

print("\r")

# using remove() to remove 1st occurrence of 1 arr.remove(1)

# printing array after removing print ("The


array after removing is : ", end ="") for i in
range (0, 3): print (arr[i], end =" ")

number = arr.array('i', [1, 2, 3, 3, 4]) del number[2]


# removing third element print(number) #
Output: array('i', [1, 2, 3, 4])

Output:
The new created array is : 1 2 3 1 5

The popped element is : 3

The array after popping is : 1 2 1 5


The array after removing is : 2 1 5
array(‘I’,*1,2,3,4+)

Slicing of a Array
In Python array, there are multiple ways to print the whole array with all the elements, but to print a
specific range of elements from the array, we use Slice operation. Slice operation is performed on
array with the use of colon(:). To print elements from beginning to a range use [:Index], to print
elements from end use [:-Index], to print elements from specific Index till the end use [Index:], to
PYHTON PROGRAMMING

print elements within a range, use [Start Index:End Index] and to print whole List with the use of
slicing operation, use [:]. Further, to print whole array in reverse order, use [::-1].

# Python program to demonstrate

# slicing of elements in a Array

# importing array module

import array as arr

# creating a list l = [1, 2, 3,


4, 5, 6, 7, 8, 9, 10]

a = arr.array('i', l)
print("Initial Array: ")
for i in (a):

print(i, end =" ")

# Print elements of a range

# using Slice operation Sliced_array =


a[3:8] print("\nSlicing elements in a range
3-8: ") print(Sliced_array)

# Print elements from a

# pre-defined point to end


Sliced_array = a[5:]
print("\nElements sliced from 5th "
"element till the end: ")

print(Sliced_array)

# Printing elements from

# beginning till end


Sliced_array = a[:]

print("\nPrinting all elements using slice operation: ") print(Sliced_array)

Output
Initial Array:
PYHTON PROGRAMMING

1 2 3 4 5 6 7 8 9 10

Slicing elements in a range 3-8:

array('i', [4, 5, 6, 7, 8])

Elements sliced from 5th element till the end:

array('i', [6, 7, 8, 9, 10])

Printing all elements using slice operation:

array('i', [1, 2, 3, 4, 5, 6, 7, 8, 9, 10])

Searching element in a Array


In order to search an element in the array we use a python in-built index() method. This function
returns the index of the first occurrence of value mentioned in arguments.

# Python code to demonstrate

# searching an element in array

# importing array module


import array

# initializing array with array values #


initializes array with signed integers

arr = array.array('i', [1, 2, 3, 1, 2, 5])

# printing original array print ("The new


created array is : ", end ="") for i in range (0,
6):

print (arr[i], end =" ")

print ("\r")

# using index() to print index of 1st occurrence of 2 print


("The index of 1st occurrence of 2 is : ", end ="") print
(arr.index(2))
PYHTON PROGRAMMING

# using index() to print index of 1st occurrence of 1 print


("The index of 1st occurrence of 1 is : ", end ="") print
(arr.index(1))

Output:

The new created array is : 1 2 3 1 2 5

The index of 1st occurrence of 2 is : 1

The index of 1st occurrence of 1 is : 0

Copy given array


import array
arr1 = array.array("i",[10, 20, 30]);
x=array.array("i") #empty array optional
x=arr1
print(x)
arr1.append(50)
print(x)

output
array('i', [10, 20, 30])
array('i', [10, 20, 30, 50])

Python Functions
A function is a block of organized, reusable code that is used to perform a single, related action.
Functions provide better modularity for your application and a high degree of code reusing.
Python gives you many built-in functions like print(), etc. but you can also create your own functions.
These functions are called user-defined functions.

Defining a Function

You can define functions to provide the required functionality.

Rules to define a function in Python.


• Function blocks begin with the keyword def followed by the function name and parentheses
( ( ) ).

• Any input parameters or arguments should be placed within these parentheses. You can also
define parameters inside these parentheses.

• The first statement of a function can be an optional statement - the documentation string of
the function or docstring.

• The code block within every function starts with a colon (:) and is indented.
PYHTON PROGRAMMING

• The statement return [expression] exits a function, optionally passing back an expression to
the caller. A return statement with no arguments is the same as return None.

Syntax

def functionname( parameters ):


"function_docstring"
function_statements return
[expression]

Example

The following function takes a string as input parameter and prints it on standard screen.

def printme( str ):


"This prints a passed string into this function"
print str return
Calling a Function

Defining a function only gives it a name, specifies the parameters that are to be included in the
function and structures the blocks of code.

Once the basic structure of a function is finalized, you can execute it by calling it from another
function or directly from the Python prompt.

Following is the example to call printme() function −

# Function definition is here def


printme( str ):
"This prints a passed string into this function" print
str
return;

# Now you can call printme function printme("I'm first


call to user defined function!") printme("Again second
call to the same function")

output

I'm first call to user defined function!

Again second call to the same function


PYHTON PROGRAMMING

Pass by reference

All parameters (arguments) in the Python language are passed by reference. It means if you change
what a parameter refers to within a function, the change also reflects back in the calling function. For
example −

# Function definition is here def


changeme( mylist ):
"This changes a passed list into this function" mylist.append([1,2,3,4]);
print ("Values inside the function: ", mylist) return

# Now you can call changeme function


mylist = [10,20,30]; changeme(
mylist );
print ("Values outside the function: ", mylist)
Here, we are maintaining reference of the passed object and appending values in the same object.
So, this would produce the following result −

Values inside the function: [10, 20, 30, [1, 2, 3, 4]]

Values outside the function: [10, 20, 30, [1, 2, 3, 4]]

There is one more example where argument is being passed by reference and the reference is being
overwritten inside the called function.

# Function definition is here def


changeme( mylist ):
"This changes a passed list into this function"
mylist = [1,2,3,4]; # This would assig new reference in mylist
print ("Values inside the function: ", mylist) return

# Now you can call changeme function


mylist = [10,20,30]; changeme(
mylist );
print ("Values outside the function: ", mylist)
The parameter mylist is local to the function changeme. Changing mylist within the function does not
affect mylist. The function accomplishes nothing and finally this would produce the following result −
Values inside the function: [1, 2, 3, 4]

Values outside the function: [10, 20, 30]

Example-3

a=[10,20,
30]
print(a)
def
sum(x):
PYHTON PROGRAMMING

x.append('bca')
print(x)

sum(a)
print(a)

Function Arguments

You can call a function by using the following types of formal arguments −

• Positional (required) arguments


• Keyword arguments
• Default arguments
• Variable-length arguments
Positional (Required) Arguments
When you call a function, Python must match each argument in the function
call with a parameter in the function definition. The simplest way to do this is
based on the order of the arguments provided. Values matched up this way are
called positional arguments.

def describe_pet(animal_type, pet_name):


"""Display information about a pet."""
print("\nIhave a " + animal_type + ".")

print("My " + animal_type + "'s name is " + pet_name + ".")

describe_pet('hamster', 'harry')

output
I have a hamster.

My hamster's name is Harry.

Example-2
To call the function printme(), you definitely need to pass one argument, otherwise it gives a syntax
error as follows −

# Function definition is here def


printme( str ):
"This prints a passed string into this function" print(str)
return

# Now you can call printme function printme()


PYHTON PROGRAMMING

When the above code is executed, it produces the following result −

Traceback (most recent call last):

File "test.py", line 11, in <module>

printme();

TypeError: printme() takes exactly 1 argument (0 given)

Keyword arguments

A keyword argument is a name-value pair that you pass to a function. You directly associate the
name and the value within the argument, so when you pass the argument to the function, there’s no
confusion (you won’t end up with a harry named Hamster). Keyword arguments free you from
having to worry about correctly ordering your arguments in the function call, and they clarify the
role of each value in the function call.

def describe_pet(animal_type, pet_name): """Display


information about a pet.""" print("\nI have a "
+ animal_type + ".")

print("My " + animal_type + "'s name is " + pet_name.title() + ".")


describe_pet(animal_type='hamster', pet_name='harry')

The function describe_pet() hasn’t changed. But when we call the function, we explicitly tell Python
which parameter each argument should be matched with. When Python reads the function call, it
knows to store the argument 'hamster' in the parameter animal_type and the argument 'harry' in
pet_name.

The output correctly shows that we have a hamster named Harry.

The order of keyword arguments doesn’t matter because Python knows where each value
should go. The following two function calls are equivalent:
describe_pet(animal_type='hamster', pet_name='harry') describe_pet(pet_name='harry',
animal_type='hamster')

Note: When you use keyword arguments, be sure to use the exact names of the parameters in

Example-2
The following example gives more clear picture. Note that the order of parameters does not matter.

# Function definition is here def


printinfo( name, age ):
PYHTON PROGRAMMING

"This prints a passed info into this function"


print ("Name: ", name) print ("Age ", age)
return

# Now you can call printinfo function printinfo(


age=50, name="miki" )
When the above code is executed, it produces the following result −

Name: miki

Age 50

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. The following example gives an idea on default arguments, it prints
default age if it is not passed −

# Function definition is here def


printinfo( name, age = 35 ):
"This prints a passed info into this function"
print ("Name: ", name) print ("Age ", age)
return

# Now you can call printinfo function


printinfo( age=50, name="miki" ) printinfo(
name="miki" )
When the above code is executed, it produces the following result −

Name: miki

Age 50

Name: miki

Age 35

Note: When you use default values, any parameter with a default value needs to be listed after all
the parameters that don’t have default values. This allows Python to continue interpreting
positional arguments correctly.

Variable-length arguments (Arbitrary Number of Arguments)

Sometimes you won’t know ahead of time how many arguments a function needs to accept.
Fortunately, Python allows a function to collect an arbitrary number of arguments from the calling
statement.
PYHTON PROGRAMMING

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.
Syntax for a function with non-keyword variable arguments is this − def
functionname([formal_args,] *var_args_tuple ):

"function_docstring"
function_statements return [expression]

An asterisk (*) is placed before the variable name that holds the values of all non keyword variable
arguments. This tuple remains empty if no additional arguments are specified during the function
call. This syntax works no matter how many arguments the function receives.

Following is a simple example –

Example-1

def make_pizza(*toppings):
"""Print the list of toppings that have been requested."""
print(toppings)
make_pizza('xyz')
make_pizza('aaa', 'bbb', 'ccc')

Example-2 Mixing Positional and Arbitrary Arguments

# Function definition is here def


printinfo( arg1, *vartuple ):
"This prints a variable passed arguments"
print ("Output is: ") print (arg1) for var in
vartuple:
print (var)
return

# Now you can call printinfo function


printinfo( 10 ) printinfo( 70, 60, 50 )
When the above code is executed, it produces the following result −

Output is:

10

Output is:

70

60

50
PYHTON PROGRAMMING

Arbitrary Keyword Arguments


If you do not know how many keyword arguments that will be passed into your function, add two
asterisk: ** before the parameter name in the function definition.

This way the function will receive a dictionary of arguments, and can access the items accordingly:

Example
If the number of keyword arguments is unknown, add a double ** before the parameter name:

def my_function(**kid):

print("His last name is " + kid["lname"])

my_function(fname = "abc", lname = "xyz")

Example-2

def build_profile(first, last, **user_info):


"""Build a dictionary containing everything we know about a
user.""" profile = {} profile['first_name'] = first
profile['last_name'] = last for key, value in user_info.items():
profile[key] = value return profile
user_profile = build_profile('albert', 'einstein',location='princeton',field='physics')
print(user_profile)

The return Statement

Python functions can return single as well as multiple values. To return multiple values, you can
return either a dictionary, a Python tuple, or a list to your main program.

The statement return [expression] exits a function, optionally passing back an expression to the
caller. A return statement with no arguments is the same as return None.

All the above examples are not returning any value. You can return a value from a function as
follows −

# Function definition is here def


sum( arg1, arg2 ):
# Add both the parameters and return them." total =
arg1 + arg2
print ("Inside the function : ", total) return
total

# Now you can call sum function


PYHTON PROGRAMMING

total = sum( 10, 20 );


print ("Outside the function : ", total )
When the above code is executed, it produces the following result −

Inside the function : 30

Outside the function : 30

Using Tuple:
# A Python program to return multiple

# values from a method using tuple

# This function returns a


tuple def fun(): str =
"palanpur"

x = 20

return (str, x ) # Return tuple # u can write also

# aa=(str,x)

#return aa

str, x = fun() # Assign returned tuple


print(str) print(x)

Output:
palanpur

20

Using a list: A list is like an array of items created using square brackets. They are different from
arrays as they can contain items of different types. Lists are different from tuples as they are
mutable.

# A Python program to return multiple

# values from a method using list

# This function returns a


list def fun(): str =
"palanpur" x = 20
return [str, x];
PYHTON PROGRAMMING

list = fun()
print(list)

Output:

['palanpur', 20]

Using a Dictionary: A Dictionary is similar to hash or map in other languages.

# A Python program to return multiple

# values from a method using dictionary

# This function returns a dictionary


def fun(): d = dict(); d['str'] =
"palanpur"

d['x'] = 20

return d

d = fun()
print(d)

Output:

{'str': 'palanpur', 'x': 20}

Python Lambda Function


A lambda function is a small anonymous function.

A lambda function can take any number of arguments, but can only have one expression.

These functions are called anonymous because they are not declared in the standard manner by using
the def keyword. You can use the lambda keyword to create small anonymous functions.
• Lambda forms can take any number of arguments but return just one value in the form of an
expression. They cannot contain commands or multiple expressions.

• An anonymous function cannot be a direct call to print because lambda requires an


expression

Syntax
PYHTON PROGRAMMING

The syntax of lambda functions contains only a single statement, which is as follows − lambda
[arg1 [,arg2,.....argn]]:expression

Following is the example to show how lambda form of function works –

Example-1
Add 10 to argument a, and return the result:

x = lambda a : a + 10
print(x(5))

output 15

Example-2

# Function definition is here


sum = lambda arg1, arg2: arg1 + arg2;

# Now you can call sum as a function print


("Value of total : ", sum( 10, 20 )) print
("Value of total : ", sum( 20, 20 ))
When the above code is executed, it produces the following result −

Value of total : 30

Value of total : 40

Python Recursive Function:


Recursion is a programming technique where a function calls itself either directly or indirectly to
solve a problem by breaking it into smaller, simpler subproblems.
In Python, recursion is especially useful for problems that can be divided into identical smaller tasks,
such as mathematical calculations, tree traversals or divide-and-conquer algorithms.
Working of Recursion
A recursive function is just like any other Python function except that it calls itself in its body. Let's
see basic structure of recursive function:
def recursive_function(parameters):
if base_case_condition:
return base_result
else:
return recursive_function(modified_parameters)

Recursive function contains two key parts:


 Base Case: The stopping condition that prevents infinite recursion.
 Recursive Case: The part of the function where it calls itself with modified parameters.
Examples of Recursion
Let's understand recursion better with the help of some examples.
PYHTON PROGRAMMING

Example 1: Factorial Calculation


This code defines a recursive function to calculate factorial of a number, where function
repeatedly calls itself with smaller values until it reaches the base case.

def factorial(n):
if n == 0: # Base case
return 1
else: # Recursive case
return n * factorial(n - 1)

print(factorial(5))

OUTPUT : 120

Explanation:
 Base Case: When n == 0, recursion stops and returns 1.
 Recursive Case: Multiplies n with the factorial of n-1 until it reaches the base case.

Example 2: Fibonacci Sequence


This code defines a recursive function to calculate nth Fibonacci number, where each number is
the sum of the two preceding ones, starting from 0 and 1.

Example 2: Fibonacci Sequence


This code defines a recursive function to calculate nth Fibonacci number, where each number is
the sum of the two preceding ones, starting from 0 and 1.
def fibonacci(n):
if n == 0:
return 0
elif n == 1:
return 1
else:
return fibonacci(n-1) + fibonacci(n-2)

print(fibonacci(10))
OUTPUT : 55

Explanation:
 Base Cases: If n == 0, the function returns 0. If n == 1, the function returns 1. These two cases
are necessary to stop the recursion.
 Recursive Case: function calls itself twice with decrements of n (i.e., fibonacci(n-1) and
fibonacci(n-2)), summing results of these calls.
PYHTON PROGRAMMING

Scope of Variables

All variables in a program may not be accessible at all locations in that program. This depends on
where you have declared a variable.

The scope of a variable determines the portion of the program where you can access a particular
identifier. There are two basic scopes of variables in Python −

• Global variables
• Local variables

Global vs. Local variables

Variables that are defined inside a function body have a local scope, and those defined outside have
a global scope.

This means that local variables can be accessed only inside the function in which they are declared,
whereas global variables can be accessed throughout the program body by all functions. When you
call a function, the variables declared inside it are brought into scope. Following is a simple example

total = 0; # This is global variable. #


Function definition is here def sum(
arg1, arg2 ):
# Add both the parameters and return them." total =
arg1 + arg2; # Here total is local variable. print ("Inside
the function local total : ", total) return total;

# Now you can call sum function


sum( 10, 20 ); print ("Outside the function global
total : ", total )

When the above code is executed, it produces the following result −

Inside the function local total : 30

Outside the function global total : 0

Passing a List as an Argument

You can send any data types of argument to a function (string, number, list, dictionary etc.), and it
will be treated as the same data type inside the function.

E.g. if you send a List as an argument, it will still be a List when it reaches the function:
PYHTON PROGRAMMING

def my_function(food):
for x in food:

print(x)

fruits = ["apple", "banana", "cherry"]

my_function(fruits)

Python Built in Functions

Python has a set of built-in functions.

Function Description

abs() Returns the absolute value of a number


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
chr() Returns a character from the specified Unicode/ASCII code.
complex() Returns a complex number
delattr() Deletes the specified attribute (property or method) from the specified object
dict() Returns a dictionary (Array)
float() Returns a floating point number
frozenset() Returns a frozenset object
getattr() Returns the value of the specified attribute (property or method)
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
len() Returns the length of an object
list() Returns a list
Returns the largest item in an iterable
Returns the smallest item in an iterable

oct() Converts a number into an octal


open() Opens a file and returns a file object
ord() Convert an integer representing the Unicode/ASCII of the specified character
pow() Returns the value of x to the power of y
print() Prints to the standard output device
PYHTON PROGRAMMING

range() Returns a sequence of numbers, starting from 0 and increments by 1 (by default)
round() Rounds a numbers
set() Returns a new set object
super() Returns an object that represents the parent class
tuple() Returns a tuple
type() Returns the type of an object

Python String Methods


Method Description
capitalize() Converts the first character to upper case
casefold() Converts string into lower case
count() Returns the number of times a specified value occurs in a string
find() Searches the string for a specified value and returns the position of where it was
found
index() Searches the string for a specified value and returns the position of where it was
found
isalnum() Returns True if all characters in the string are alphanumeric
isalpha() Returns True if all characters in the string are in the alphabet
isdecimal() Returns True if all characters in the string are decimals
isdigit() Returns True if all characters in the string are digits
islower() Returns True if all characters in the string are lower case
isnumeric() Returns True if all characters in the string are numeric
isspace() Returns True if all characters in the string are whitespaces
istitle() Returns True if the string follows the rules of a title
isupper() Returns True if all characters in the string are upper case
lower() Converts a string into lower case
partition() Returns a tuple where the string is parted into three parts
replace() Returns a string where a specified value is replaced with a specified value
rfind() Searches the string for a specified value and returns the last position of where it
was found
rindex() Searches the string for a specified value and returns the last position of where it
was found
rpartition() Returns a tuple where the string is parted into three parts
rsplit() Splits the string at the specified separator, and returns a list
rstrip() Returns a right trim version of the string
split() Splits the string at the specified separator, and returns a list
splitlines() Splits the string at line breaks and returns a list
startswith() Returns true if the string starts with the specified value
strip() Returns a trimmed version of the string
swapcase() Swaps cases, lower case becomes upper case and vice versa
title() Converts the first character of each word to upper case
upper() Converts a string into upper case
PYHTON PROGRAMMING

Python List/Array Methods


Method Description
append() Adds an element at the end of the list
clear() Removes all the elements from the list
copy() Returns a copy of the list
count() Returns the number of elements with the specified value
extend() Add the elements of a list (or any iterable), to the end of the current list
index() Returns the index of the first element with the specified value
insert() Adds an element at the specified position
pop() Removes the element at the specified position
remove() Removes the first item with the specified value
reverse() Reverses the order of the list
sort() Sorts the list
Python Set Methods
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
discard() Remove the specified item
intersection() Returns a set, that is the intersection of two or more sets
union() Returns a set, that is the union of two or more sets
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

Python Modules
What is a Module?
Consider a module to be the same as a code library.

A file containing a set of functions you want to include in your application.

Create a Module
To create a module just save the code you want in a file with the file extension .py:

Example
PYHTON PROGRAMMING

Save the code in file named mymodule.py def


greeting(name):

print("Hello, " + name)

Use a Module
Now we can use the module we just created, by using the import statement:
Example
Import the module named mymodule, and call the greeting function:
import mymodule

mymodule.greeting("Jonathan")

Creating our own modules in python.

Storing Your Functions in Modules


• One advantage of functions is the way they separate blocks of code from your main
program. You can go a step further by storing your functions in a separate file called a
module and then importing that module into your main program.
• An import statement tells Python to make the code in a module available in the currently
running program file.
• Storing your functions in a separate file allows you to hide the details of your program’s
code and focus on its higher-level logic.
• It also allows you to reuse functions in many different programs. When you store your
functions in separate files, you can share those files with other programmers without having
to share your entire program. Knowing how to import functions also allows you to use
libraries of functions that other programmers have written.
There are several ways to import a module.

Importing an Entire Module

• To start importing functions, we first need to create a module.


• A module is a file ending in .py that contains the code you want to import into your program.
Let’s make a module that contains the function make_pizza().
• To make this module, pizza.py

def make_pizza(size, *toppings):

"""Summarize the pizza we are about to make.""" print("\nMaking a " ,


size ,"-inch pizza with the following toppings:") for topping in toppings:

print("- " + topping)

Now we’ll make a separate file called making_pizzas.py in the same directory as pizza.py. This file
imports the module we just created and then makes two calls to make_pizza():
PYHTON PROGRAMMING

import pizza

pizza.make_pizza(16, 'pepperoni')

pizza.make_pizza(12, 'mushrooms', 'green peppers', 'extra cheese')

Output

Making a 16-inch pizza with the following toppings:

- pepperoni
Making a 12-inch pizza with the following toppings:

- mushrooms
- green peppers
- extra cheese

This first approach to importing, in which you simply write import followed by the name of the
module, makes every function from the module available in your program. If you use this kind of
import statement to import an entire module named module_name.py, each function in the module
is available through the following syntax:

syntax

module_name.function_name()

Importing Specific Functions


You can also import a specific function from a module. Here’s the general syntax for this approach:

from module_name import function_name

You can import as many functions as you want from a module by separating each function’s name
with a comma:

from module_name import function_0, function_1, function_2

The making_pizzas.py example would look like this if we want to import just the function we’re
going to use:

from pizza import make_pizza make_pizza(16,


'pepperoni')
PYHTON PROGRAMMING

make_pizza(12, 'mushrooms', 'green peppers', 'extra cheese')

With this syntax, you don’t need to use the dot notation when you call a function. Because we’ve
explicitly imported the function make_pizza() in the import statement, we can call it by name when
we use the function.

Using as to Give a Function an Alias


If the name of a function you’re importing might conflict with an existing name in your
program or if the function name is long, you can use a short, unique alias—an alternate
name similar to a nickname for the function.

You’ll give the function this special nickname when you import the function.

Here we give the function make_pizza() an alias, mp(), by importing make_pizza as mp. The as
keyword renames a function using the alias you provide:

from pizza import make_pizza as mp

mp(16, 'pepperoni')

mp(12, 'mushrooms', 'green peppers', 'extra cheese')

The import statement shown here renames the function make_pizza() to mp() in this program. Any
time we want to call make_pizza() we can simply write mp() instead, and Python will run the code in
make_pizza() while avoiding any confusion with another make_pizza() function you might have
written in this program file.

The general syntax for providing an alias is:

from module_name import function_name as fn

Using as to Give a Module an Alias


• You can also provide an alias for a module name. Giving a module a short alias, like p for
pizza, allows you to call the module’s functions more quickly.
• Calling p.make_pizza() is more concise than calling pizza.make_pizza():
import pizza as p

p.make_pizza(16, 'pepperoni')

p.make_pizza(12, 'mushrooms', 'green peppers', 'extra cheese')

• The module pizza is given the alias p in the import statement, but all of the module’s
functions retain their original names. Calling the functions by writing p.make_pizza() is not
only more concise than writing pizza.make_pizza(),but also redirects your attention from the
module name and allows you to focus on the descriptive names of its
PYHTON PROGRAMMING

functions. These function names, which clearly tell you what each function does, are more
important to the readability of your code than using the full module name.

• The general syntax for this approach is: import module_name as mn

Importing All Functions in a Module


You can tell Python to import every function in a module by using the asterisk (*) operator:

from pizza import *


make_pizza(16, 'pepperoni')

make_pizza(12, 'mushrooms', 'green peppers', 'extra cheese')

The asterisk in the import statement tells Python to copy every function from the module pizza into
this program file.

from module_name import *

Variables in Module

The module can contain functions, as already described, but also variables of all types (arrays,
dictionaries, objects etc):

Example
The module named mymodule has one function and one dictionary:

def greeting(name):
print("Hello, " + name)

person1 = {
"name": "John",
"age": 36,
"country": "Norway"
}

Example
Import only the person1 dictionary from the module:
from mymodule import person1

print (person1["age"])
PYHTON PROGRAMMING

Packages

Python packages are a way to organize and structure code by grouping related modules into
directories. A package is essentially a folder that contains an __init__.py file and one or more Python
files (modules). This organization helps manage and reuse code effectively, especially in larger
projects. It also allows functionality to be easily shared and distributed across different applications.
Packages act like toolboxes, storing and organizing tools (functions and classes) for efficient access
and reuse.
Key Components of a Python Package
 Module: A single Python file containing reusable code (e.g., math.py).
 Package: A directory containing modules and a special __init__.py file.
 Sub-Packages: Packages nested within other packages for deeper organization.

How to create and access packages in python


1. Create a Directory: Make a directory for your package. This will serve as the root folder.
2. Add Modules: Add Python files (modules) to the directory, each representing specific
functionality.
3. Include __init__.py: Add an __init__.py file (can be empty) to the directory to mark it as a
package.
4. Add Sub packages (Optional): Create subdirectories with their own __init__.py files for sub
packages.
5. Import Modules: Use dot notation to import, e.g., from mypackage.module1 import greet.

Example :
In this example, we are creating a Math Operation Package to organize Python code into a
structured package with two sub-packages: basic (for addition and subtraction) and advanced (for
multiplication and division). Each operation is implemented in separate modules, allowing for
modular, reusable and maintainable code.
math_operations/__init__.py:
This __init__.py file initializes the main package by importing and exposing the calculate function
and operations (add, subtract, multiply, divide) from the respective sub-packages for easier
access.

# Initialize the main package

from .calculate import calculate

from .basic import add, subtract

from .advanced import multiply, divide

math_operations/calculator.py:
This calculate file is a simple placeholder that prints "Performing calculation...", serving as a basic
demonstration or utility within the package.

def calculate():
PYHTON PROGRAMMING

print("Performing calculation...")

math_operations/basic/__init__.py:
This __init__.py file initializes the basic sub-package by importing and exposing the add and
subtract functions from their respective modules (add.py and sub.py). This makes these functions
accessible when the basic sub-package is imported.
# Export functions from the basic sub-package

from .add import add

from .sub import subtract

math_operations/basic/add.py:

def add(a, b):

return a + b

math_operations/basic/sub.py:

def subtract(a, b):

return a – b

In the same way we can create the sub package advanced with multiply and divide modules. Now,
let's take an example of importing the module into a code and using the function:

from math_operations import calculate, add, subtract

# Using the placeholder calculate function

calculate()

# Perform basic operations

print("Addition:", add(5, 3))

print("Subtraction:", subtract(10, 4))

Output:
6
8
PYHTON PROGRAMMING

Python Packages

Suppose you have developed a very large application that includes many modules. As the number of
modules grows, it becomes difficult to keep track of them all if they are dumped into one location.
This is particularly so if they have similar names or functionality. You might wish for a means of
grouping and organizing them.

Packages allow for a hierarchical structuring of the module namespace using dot notation. In the
same way that modules help avoid collisions between global variable names, packages help avoid
collisions between module names.

Creating a package is quite straightforward, since it makes use of the operating system’s inherent
hierarchical file structure. Consider the following arrangement:

Here, there is a directory named pkg that contains two modules, mod1.py and mod2.py. The
contents of the modules are:

mod1.py
PYHTON PROGRAMMING

def foo():
print('[mod1] foo()')

class Foo:
pass
mod2.py

def bar():
print('[mod2] bar()')

class Bar:
pass
Given this structure, if the pkg directory resides in a location where it can be found (in one of the
directories contained in sys.path), you can refer to the two modules with dot
notation (pkg.mod1, pkg.mod2) and import them with the syntax you are already familiar with:

import <module_name>[, <module_name> ...]


>>> import pkg.mod1, pkg.mod2
>>> pkg.mod1.foo()
[mod1] foo()
>>> x = pkg.mod2.Bar()
>>> x
<pkg.mod2.Bar object at 0x033F7290>
from <module_name> import <name(s)>
>>> from pkg.mod1 import foo
>>> foo()
[mod1] foo()
from <module_name> import <name> as <alt_name>
>>> from pkg.mod2 import Bar as Qux
>>> x = Qux()
>>> x
<pkg.mod2.Bar object at 0x036DFFD0>
You can import modules with these statements as well:

from <package_name> import <modules_name>[, <module_name> ...]


from <package_name> import <module_name> as <alt_name>
>>> from pkg import mod1
>>> mod1.foo()
[mod1] foo()
PYHTON PROGRAMMING

>>> from pkg import mod2 as quux


>>> quux.bar()
[mod2] bar()
You can technically import the package as well:

>>> import pkg


>>> pkg
<module 'pkg' (namespace)>
But this is of little avail. Though this is, strictly speaking, a syntactically correct Python statement, it
doesn’t do much of anything useful. In particular, it does not place any of the modules in pkg into
the local namespace:

>>> pkg.mod1
Traceback (most recent call last):
File "<pyshell#34>", line 1, in <module>
pkg.mod1
AttributeError: module 'pkg' has no attribute 'mod1'
>>> pkg.mod1.foo()
Traceback (most recent call last):
File "<pyshell#35>", line 1, in <module>
pkg.mod1.foo()
AttributeError: module 'pkg' has no attribute 'mod1'
>>> pkg.mod2.Bar()
Traceback (most recent call last):
File "<pyshell#36>", line 1, in <module>
pkg.mod2.Bar()
AttributeError: module 'pkg' has no attribute 'mod2'
To actually import the modules or their contents, you need to use one of the forms shown above.

Package Initialization

If a file named __init__.py is present in a package directory, it is invoked when the package or a
module in the package is imported. This can be used for execution of package initialization code,
such as initialization of package-level data.

For example, consider the following __init__.py file:

__init__.py

print(f'Invoking __init__.py for {__name__}')


A = ['quux', 'corge', 'grault']
PYHTON PROGRAMMING

Let’s add this file to the pkg directory from the above example:

Now when the package is imported, the global list A is initialized:

>>> import pkg


Invoking __init__.py for pkg
>>> pkg.A
['quux', 'corge', 'grault']
A module in the package can access the global variable by importing it in turn:

mod1.py

def foo():
from pkg import A
print('[mod1] foo() / A = ', A)

class Foo:
pass
>>> from pkg import mod1
Invoking __init__.py for pkg
>>> mod1.foo()
[mod1] foo() / A = ['quux', 'corge', 'grault']
__init__.py can also be used to effect automatic importing of modules from a package. For example,
earlier you saw that the statement import pkg only places the name pkg in the caller’s local symbol
table and doesn’t import any modules. But if __init__.py in the pkg directory contains the following:

__init__.py

print(f'Invoking __init__.py for {__name__}')


import pkg.mod1, pkg.mod2
then when you execute import pkg, modules mod1 and mod2 are imported automatically:

>>> import pkg


Invoking __init__.py for pkg
PYHTON PROGRAMMING

>>> pkg.mod1.foo()
[mod1] foo()
>>> pkg.mod2.bar()
[mod2] bar()
Note: Much of the Python documentation states that an __init__.py file must be present in the
package directory when creating a package. This was once true. It used to be that the very presence
of __init__.py signified to Python that a package was being defined. The file could contain
initialization code or even be empty, but it had to be present.

Starting with Python 3.3, Implicit Namespace Packages were introduced. These allow for the
creation of a package without any __init__.py file. Of course, it can still be present if package
initialization is needed. But it is no longer required. Check out What’s a Python Namespace Package,
and What’s It For? to learn more.
Importing * From a Package

For the purposes of the following discussion, the previously defined package is expanded to contain
some additional modules:

There are now four modules defined in the pkg directory. Their contents are as shown below:

mod1.py

def foo():
print('[mod1] foo()')

class Foo:
pass
mod2.py

def bar():
print('[mod2] bar()')

class Bar:
PYHTON PROGRAMMING

pass
mod3.py

def baz():
print('[mod3] baz()')

class Baz:
pass
mod4.py

def qux():
print('[mod4] qux()')

class Qux:
pass
(Imaginative, aren’t they?)

You have already seen that when import * is used for a module, all objects from the module are
imported into the local symbol table, except those whose names begin with an underscore, as
always:

>>> dir()
['__annotations__', '__builtins__', '__doc__', '__loader__', '__name__',
'__package__', '__spec__']

>>> from pkg.mod3 import *

>>> dir()
['Baz', '__annotations__', '__builtins__', '__doc__', '__loader__', '__name__',
'__package__', '__spec__', 'baz']
>>> baz()
[mod3] baz()
>>> Baz
<class 'pkg.mod3.Baz'>
The analogous statement for a package is this:

from <package_name> import *


What does that do?

>>> dir()
['__annotations__', '__builtins__', '__doc__', '__loader__', '__name__',
'__package__', '__spec__']
PYHTON PROGRAMMING

>>> from pkg import *


>>> dir()
['__annotations__', '__builtins__', '__doc__', '__loader__', '__name__',
'__package__', '__spec__']
Hmph. Not much. You might have expected (assuming you had any expectations at all) that Python
would dive down into the package directory, find all the modules it could, and import them all. But
as you can see, by default that is not what happens.

Instead, Python follows this convention: if the __init__.py file in the package directory contains
a list named __all__, it is taken to be a list of modules that should be imported when the
statement from <package_name> import * is encountered.

For the present example, suppose you create an __init__.py in the pkg directory like this:

pkg/__init__.py

__all__ = [
'mod1',
'mod2',
'mod3',
'mod4'
]
Now from pkg import * imports all four modules:

>>> dir()
['__annotations__', '__builtins__', '__doc__', '__loader__', '__name__',
'__package__', '__spec__']

>>> from pkg import *


>>> dir()
['__annotations__', '__builtins__', '__doc__', '__loader__', '__name__',
'__package__', '__spec__', 'mod1', 'mod2', 'mod3', 'mod4']
>>> mod2.bar()
[mod2] bar()
>>> mod4.Qux
<class 'pkg.mod4.Qux'>
Using import * still isn’t considered terrific form, any more for packages than for modules. But this
facility at least gives the creator of the package some control over what happens when import * is
specified. (In fact, it provides the capability to disallow it entirely, simply by declining to
define __all__ at all. As you have seen, the default behavior for packages is to import nothing.)
PYHTON PROGRAMMING

By the way, __all__ can be defined in a module as well and serves the same purpose: to control
what is imported with import *. For example, modify mod1.py as follows:

pkg/mod1.py

__all__ = ['foo']

def foo():
print('[mod1] foo()')

class Foo:
pass
Now an import * statement from pkg.mod1 will only import what is contained in __all__:

>>> dir()
['__annotations__', '__builtins__', '__doc__', '__loader__', '__name__',
'__package__', '__spec__']

>>> from pkg.mod1 import *


>>> dir()
['__annotations__', '__builtins__', '__doc__', '__loader__', '__name__',
'__package__', '__spec__', 'foo']

>>> foo()
[mod1] foo()
>>> Foo
Traceback (most recent call last):
File "<pyshell#37>", line 1, in <module>
Foo
NameError: name 'Foo' is not defined
foo() (the function) is now defined in the local namespace, but Foo (the class) is not, because the
latter is not in __all__.

In summary, __all__ is used by both packages and modules to control what is imported when import
* is specified. But the default behavior differs:

 For a package, when __all__ is not defined, import * does not import anything.
 For a module, when __all__ is not defined, import * imports everything (except—you
guessed it—names starting with an underscore).
PYHTON PROGRAMMING

Subpackages

Packages can contain nested subpackages to arbitrary depth. For example, let’s make one more
modification to the example package directory as follows:

The four modules (mod1.py, mod2.py, mod3.py and mod4.py) are defined as previously. But now,
instead of being lumped together into the pkg directory, they are split out into
two subpackage directories, sub_pkg1 and sub_pkg2.

Importing still works the same as shown previously. Syntax is similar, but additional dot notation is
used to separate package name from subpackage name:

>>> import pkg.sub_pkg1.mod1


>>> pkg.sub_pkg1.mod1.foo()
[mod1] foo()

>>> from pkg.sub_pkg1 import mod2


>>> mod2.bar()
[mod2] bar()

>>> from pkg.sub_pkg2.mod3 import baz


>>> baz()
[mod3] baz()

>>> from pkg.sub_pkg2.mod4 import qux as grault


>>> grault()
[mod4] qux()
PYHTON PROGRAMMING

In addition, a module in one subpackage can reference objects in a sibling subpackage (in the event
that the sibling contains some functionality that you need). For example, suppose you want to
import and execute function foo() (defined in module mod1) from within module mod3. You can
either use an absolute import:

pkg/sub__pkg2/mod3.py

def baz():
print('[mod3] baz()')

class Baz:
pass

from pkg.sub_pkg1.mod1 import foo


foo()
>>> from pkg.sub_pkg2 import mod3
[mod1] foo()
>>> mod3.foo()
[mod1] foo()
Or you can use a relative import, where .. refers to the package one level up. From within mod3.py,
which is in subpackage sub_pkg2,

 .. evaluates to the parent package (pkg), and


 ..sub_pkg1 evaluates to subpackage sub_pkg1 of the parent package.

pkg/sub__pkg2/mod3.py

def baz():
print('[mod3] baz()')

class Baz:
pass

from .. import sub_pkg1


print(sub_pkg1)

from ..sub_pkg1.mod1 import foo


foo()
>>> from pkg.sub_pkg2 import mod3
<module 'pkg.sub_pkg1' (namespace)>
[mod1] foo()
PYHTON PROGRAMMING

Conclusion

In this tutorial, you covered the following topics:

 How to create a Python module


 Locations where the Python interpreter searches for a module
 How to obtain access to the objects defined in a module with the import statement
 How to create a module that is executable as a standalone script
 How to organize modules into packages and subpackages
 How to control package initialization

You might also like