0% found this document useful (0 votes)
3 views51 pages

Unit2 Python

The document provides an overview of functions in Python, explaining user-defined functions, their declaration, and calling methods. It covers parameters, default arguments, lambda functions, and string manipulation, including string slicing and methods. Key points emphasize the importance of function definition, the immutability of strings, and various ways to handle parameters in functions.

Uploaded by

veena more
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)
3 views51 pages

Unit2 Python

The document provides an overview of functions in Python, explaining user-defined functions, their declaration, and calling methods. It covers parameters, default arguments, lambda functions, and string manipulation, including string slicing and methods. Key points emphasize the importance of function definition, the immutability of strings, and various ways to handle parameters in functions.

Uploaded by

veena more
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

UNIT2 FUNCTIONS 1

FUNCTIONS
A function is a block of reusable code that performs a specific task. It helps
reduce code duplication and improves modularity.
DECLARING AND CALLING USER DEFINED FUNCTIONS
 A user-defined function (UDF) is a function created by the user to perform
specific tasks in a program.
 Unlike built-in functions provided by a programming language, udfs allow
for customization and code reusability, improving program structure and
efficiency.

Declaring and calling user-defined functions in Python involves two main steps:
defining the function and then invoking it.
1. Declaring (Defining) a User-Defined Function:
 A function definition begins with the def keyword, followed by the function
name, a set of parentheses (), and a colon :.
 Parameters, if any, are listed inside the parentheses.
 The function body, containing the code to be executed when the function
is called, is indented below the def line.
 An optional return statement can be used to send a value back to the
caller.
 If return is omitted, the function implicitly returns None.

2. Calling (Invoking) a User-Defined Function:


 To execute the code within a defined function, call it by its name followed
by parentheses ().

[Link] College of Commerce (Autonomous), Vijayapur BCA


Programme
UNIT2 FUNCTIONS 2

 If the function was defined with parameters, provide corresponding


arguments inside the parentheses during the call.

# function definition
def fun( x ):
if (x % 2 == 0):
print("even")
else:
print("odd")
fun(2) # function calling

Example: Function Without Parameters


def greet():
print("Hello, welcome to Python!")
# Calling the function
greet()
Output
Hello, welcome to Python!

Example: Function With Parameters


def greet_user(name):
print(f"Hello {name}, welcome to Python!")
# Calling the function
greet_user(“Alice")
[Link] College of Commerce (Autonomous), Vijayapur BCA
Programme
UNIT2 FUNCTIONS 3

Output:
Hello Alice, welcome to Python!

EXAMPLE: Function With Return Value


def add_numbers(a, b):
return a + b
# Calling and storing the result
result = add_numbers(10, 20)
print("Sum:", result)
Output:
Sum: 30

EXAMPLE: Multiple Parameters & Default Arguments


def introduce(name, language="Python"):
print(f"My name is {name} and MY favourite language is {language}.")
introduce(“Alice") # Uses default "Python"
introduce(“Bob", "Java") # Overrides default
Output:
My name is Alice and MY favourite language is Python.
My name is Bob and MY favourite language is Java.

Key Points to Remember


• Define first, call later – you must declare a function before calling
it.
• Functions can take zero or more parameters.
• The return statement is optional — without it, the function returns
None.
• Use docstrings ("""...""") to document your function.
[Link] College of Commerce (Autonomous), Vijayapur BCA
Programme
UNIT2 FUNCTIONS 4

PARAMETERS AND DEFAULT ARGUMENTS


Parameters
Parameters are variables listed inside the parentheses in the function definition.
They allow you to pass values (called arguments) into a function.
def greet_user(name):
print(f"Hello {name}, welcome to Python!")
# Calling the function
greet_user(“Alice")
Output:
Hello Alice, welcome to Python!
Types of Parameters:
1. Positional Parameters → matched by position.
2. Keyword Parameters → matched by name when calling the function.
3. Default Parameters → have pre-defined values.
4. Variable-length Parameters → *args (tuple) and **kwargs (dictionary).

1. Positional Parameters
• Arguments are matched to parameters by their position in the function call.
• Order matters.
EXAMPLE:
def student_info(name, age):
print(f"Name: {name}, Age: {age}")
student_info(“Andrew", 20) # Position: name → " Andrew ", age → 20
OUTPUT
Name: Andrew, Age: 20

[Link] College of Commerce (Autonomous), Vijayapur BCA


Programme
UNIT2 FUNCTIONS 5

2. Keyword Parameters
• Arguments are matched to parameters by name.
• Order does not matter when using keywords.
EXAMPLE:
def student_info(name, age):
print(f"name: {name}, age: {age}")
student_info(age=20, name=“Andrew")
OUTPUT
name: Andrew, age: 20

3. Default Parameters
• Parameters with a pre-defined value in the function definition.
• If no argument is provided, the default is used.
EXAMPLE:
def student_info(name, age=18):
print(f"Name: {name}, Age: {age}")
student_info(“bob") # Uses default age
student_info("John", 21) # Overrides default age
OUTPUT:
Name: bob, Age: 18
Name: John, Age: 21

4. Variable-length Parameters
Used when you don’t know the number of arguments in advance.
a) *args → non-keyword arguments
Collects extra positional arguments into a tuple.
EXAMPLE:

[Link] College of Commerce (Autonomous), Vijayapur BCA


Programme
UNIT2 FUNCTIONS 6

def display_numbers(*args):
print("Numbers:", args)
display_numbers(1, 2, 3, 4)
OUTPUT:
Numbers: (1, 2, 3, 4)

b)**kwargs → keyword arguments


collects extra keyword arguments into a dictionary.
EXAMPLE:
def display_info(**kwargs):
print("Info:", kwargs)
display_info(name=“John", age=20, city="Pune")
OUTPUT:
Info: {'name': ‘John', 'age': 20, 'city': 'Pune'}

LAMBDA-FUNCTIONS AS OBJECTS
 A lambda function is a small, anonymous function in python.
 Created using the lambda keyword instead of def.
 A lambda function can take any number of arguments, but can only have
one expression.
Syntax
lambda arguments : expression
EXAMPLE
square = lambda x: x * x
print(square(5))
OUTPUT
25

[Link] College of Commerce (Autonomous), Vijayapur BCA


Programme
UNIT2 FUNCTIONS 7

Here, square is actually a function object created by the lambda expression.

Lambda functions are objects


• In python:
• Functions (normal or lambda) are first-class objects.
[Link] College of Commerce (Autonomous), Vijayapur BCA
Programme
UNIT2 FUNCTIONS 8

• This means you can:


• Assign them to variables
• Pass them as arguments to other functions
• Return them from functions
• Store them in data structures (lists, dicts, etc.)
MAP FUNCTION

When the same program is rewritten using lambda function, it becomes more
elegant. This is done in program 34.

[Link] College of Commerce (Autonomous), Vijayapur BCA


Programme
UNIT2 FUNCTIONS 9

it is possible to use map() function on more than one list if the lists are of same
length. in this case, map() function takes the lists as arguments of the lambda
function and does the operation. for example,
map(lambda x, y: x*y, lst1, lst2)
here, lambda function has two arguments ‘x' and y'. hence, ‘x' represents ‘lst1' and
‘y’ represents ‘lst2’. since lambda is showing x*y, the respective elements from lst1
and lst2 are multiplied and the product is returned.
A Python program to find the products of elements of two different lists
using lambda function.
# Lambda that returns products of elements of two lists
lst1 = [1, 2, 3, 4, 5]
lst2 = [10, 20, 30, 40, 50]
lst3 = list(map(lambda x, y: x*y, lst1, lst2))
print(lst3)
Output:
[10, 40, 90, 160, 250]

STRINGS
 A string is a sequence of characters.
 Python treats anything inside quotes as a string.
 This includes letters, numbers, and symbols. Python has no character data
type so single character is a string of length 1.
 We can create a string in python by assigning a group of characters to a
variable
Creating a String
• Strings can be created using either single (') or double (") quotes.

[Link] College of Commerce (Autonomous), Vijayapur BCA


Programme
UNIT2 FUNCTIONS 10

s1 = ‘Welcome to Core Python learning’


s2 ="Welcome to Core Python learning
Multi-line Strings
if we need a string to span multiple lines then we can use triple quotes (''' or
""").
s = """i am learning
python string """
print(s)
s = '''i'm a
string'''
print(s)
output
i am learning
python string
'i'm a
string'

A string is a sequence
• A string is a sequence of characters. You can access the characters one at a
time with the bracket operator:
• The expression in brackets is called an index. The index indicates which
character in the Sequence you want.
• But for computer scientists, the index is an offset from the beginning of the
string, and the offset of the first letter is zero.
example
>>>fruit = 'banana'
>>> letter = fruit[1]
>>>letter
‘a’ //output
[Link] College of Commerce (Autonomous), Vijayapur BCA
Programme
UNIT2 FUNCTIONS 11

example
>>> letter = fruit[0]
>>> letter
‘b’
example
As an index you can use an expression that contains variables and operators:
>>> i = 1
>>> fruit[i]
'a'
>>> fruit[i+1]
'n'
but the value of the index has to be an integer. otherwise you get:
>>> letter = fruit[1.5]
typeerror: string indices must be integers
len
len is a built-in function that returns the number of characters in a string:
>>> fruit = 'banana'
>>> len(fruit)
6
To get the last letter of a string, you might be tempted to try something like this:
>>> length = len(fruit)
>>> last = fruit[length]
Indexerror: string index out of range
The reason for the Indexerror is that there is no letter in 'banana' with the index 6.
since
we started counting at zero, the six letters are numbered 0 to 5. to get the last
character,
you have to subtract 1 from length:
[Link] College of Commerce (Autonomous), Vijayapur BCA
Programme
UNIT2 FUNCTIONS 12

>>> last = fruit[length-1]


>>> last
'a'
or you can use negative indices, which count backward from the end of the string.
The expression fruit[-1] yields the last letter, fruit[-2] yields the second to last, and
so on.
Traversal with a for loop
• a lot of computations involve processing a string one character at a time.
• often they start at the beginning, select each character in turn, do something
to it, and continue until the end.
• this pattern of processing is called a traversal. one way to write a traversal
is with a while loop:
index = 0
while index < len(fruit):
letter = fruit[index]
print(letter)
index = index + 1
• this loop traverses the string and displays each letter on a line by itself.
• the loop condition is index < len(fruit), so when index is equal to the length
of the string, the condition is false, and the body of the loop doesn’t run.
• the last character accessed is the one with the index len(fruit)-1, which is the
last character in the string.
another way to write a traversal is with a for loop:
for letter in fruit:
print(letter)
• Each time through the loop, the next character in the string is assigned to
the variable Letter.
• The loop continues until no characters are left.
String slices

[Link] College of Commerce (Autonomous), Vijayapur BCA


Programme
UNIT2 FUNCTIONS 13

A segment of a string is called a slice. Selecting a slice is similar to selecting a


character:
>>> s = 'Monty Python'
>>> s[0:5]
'Monty'
>>> s[6:12]
'Python'
• The operator [n:m] returns the part of the string from the “n-eth” character to
the “m-eth” Character, including the first but excluding the last.
• If you omit the first index (before the colon), the slice starts at the beginning
of the string. If you omit the second index, the slice goes to the end of the
string:
>>> fruit = 'banana'
>>> fruit[:3]
'ban'
>>> fruit[3:]
'ana’
• If the first index is greater than or equal to the second the result is an empty
string, represented by two quotation marks:
>>> fruit = 'banana'
>>> fruit[3:3]
‘ ‘
• an empty string contains no characters and has length 0, but other than that,
it is the same as any other string.
>>>fruit[:] means all character
'banana'
Strings Are Immutable
• In python, strings are immutable, meaning once a string is created, it
cannot be changed in place.

[Link] College of Commerce (Autonomous), Vijayapur BCA


Programme
UNIT2 FUNCTIONS 14

Why python makes strings immutable:


• Efficiency — immutable objects can be stored and reused without worrying
they’ll be changed elsewhere.
Example
>>> greeting = 'hello, world!'
>>> greeting[0] = 'j’
Typeerror: 'str' object does not support item assignment
• The reason for the error is that strings are immutable, which means you
can’t change an Existing string.
• The best you can do is create a new string that is a variation on the original:
>>> greeting = 'hello, world!'
>>> new_greeting = 'j' + greeting[1:]
>>> new_greeting
'jello, world!'
• This example concatenates a new first letter onto a slice of greeting. It has
no effect on the Original string.
Searching
What does the following function do?
def find(word, letter):
index = 0
while index < len(word):
if word[index] == letter:
return index
index = index + 1
return -1
• Instead of taking an index and extracting The corresponding character, it
takes a character and finds the index where that character Appears.
• If the character is not found, the function returns -1.

[Link] College of Commerce (Autonomous), Vijayapur BCA


Programme
UNIT2 FUNCTIONS 15

• This is the first example we have seen of a return statement inside a loop.
• If word[index] == Letter, the function breaks out of the loop and returns
immediately.
• If the character doesn’t appear in the string, the program exits the loop
normally and returns -1.
• This pattern of computation—traversing a sequence and returning when we
find what we Are looking for—is called a search.
Looping and counting
the following program counts the number of times the letter a appears in a
string:
word = 'banana'
count = 0
for letter in word:
if letter == 'a’:
count = count + 1
print(count)
• this program demonstrates another pattern of computation called a counter.
the variable
• count is initialized to 0 and then incremented each time an a is found. when
the loop exits,
• count contains the result—the total number of a’s.
String methods
• strings provide methods that perform a variety of useful operations. a
method is similar to a function—it takes arguments and returns a value—but
the syntax is different.
• for example, the method upper takes a string and returns a new string with
all uppercase letters. instead of the function syntax upper(word), it uses the
method syntax [Link]().
>>> word = 'banana'
>>> new_word = [Link]()

[Link] College of Commerce (Autonomous), Vijayapur BCA


Programme
UNIT2 FUNCTIONS 16

>>> new_word
'BANANA'
• This form of dot notation specifies the name of the method, upper, and the
name of the String to apply the method to, word. the empty parentheses
indicate that this method takes no arguments.
• A method call is called an invocation; in this case, we would say that we
are invoking upper on word. as it turns out, there is a string method named
find that is remarkably similar to the function we wrote:
>>> word = 'banana'
>>> index = [Link]('a')
>>> index
1
 In this example, we invoke find on word and pass the letter we are looking
for as a parameter.
 Actually, the find method is more general than our function; it can find
substrings, not just characters:
>>> [Link]('na’)
2
By default, find starts at the beginning of the string, but it can take a second
argument, the index where it should start:
>>> [Link]('na', 3)
4
find() searches for the substring 'na' inside the string word

[Link] College of Commerce (Autonomous), Vijayapur BCA


Programme
UNIT2 FUNCTIONS 17

• the second argument 3 means start searching from index 3 (not from the
beginning).
• if it finds 'na', it returns the index of the first character of the match.
• if it doesn’t find it, it returns -1.
• this is an example of an optional argument; find can also take a third
argument, the index where it should stop:
>>> name = 'bob'
>>> [Link]('b', 1, 2)
-1
• this search fails because b does not appear in the index range from 1 to 2,
not including 2. searching up to, but not including, the second index makes
find consistent with the slice operator.
The in operator
The word in is a boolean operator that takes two strings and returns true if the
first appears as a substring in the second:
>>> 'a' in 'banana’
true
>>> 'seed' in 'banana’
false
String comparison
• the relational operators work on strings. to see if two strings are equal:
if word == 'banana’:
print('all right, bananas.')
• other relational operations are useful for putting words in alphabetical order:
if word < 'banana’:
print('your word, ' + word + ', comes before banana.')
elif word > 'banana’:
print('your word, ' + word + ', comes after banana.')
else:
[Link] College of Commerce (Autonomous), Vijayapur BCA
Programme
UNIT2 FUNCTIONS 18

print('all right, bananas.')

• Python does not handle uppercase and lowercase letters the same way
people do. All the Uppercase letters come before all the lowercase letters,
so:
Your word, pineapple, comes before banana.
• A common way to address this problem is to convert strings to a standard
format, such asAll lowercase, before performing the comparison. Keep that
in mind in case you have toDefend yourself against a man armed with a
pineapple.

indexing
Index represents the position number. Index is written using square braces []. by
specifying the position number through an index, we can refer to the individual
elements (or characters) of a string, starting from 0. we can access characters in a
string in two ways :
1. Accessing characters by positive index number
2. Accessing characters by negative index number (reverse order)

Accessing by Positive Index Number


s = “core python!"
# accessing the character of str at 0th index
print(s[0])
# accessing the character of str at 6th index

[Link] College of Commerce (Autonomous), Vijayapur BCA


Programme
UNIT2 FUNCTIONS 19

print(s[6])
# accessing the character of str at 10th index
print(s[10])
OUTPUT
c
y
n
Accessing by Negative Index Number
In this type of indexing, we pass the negative index(which we want to access) in
square brackets. Here the index number starts from index number -1 (which
denotes the last character of a string).

s = “core python!"
# accessing the character of str at 0th index
print(s[-1])
# accessing the character of str at 6th index
print(s[-5])
# accessing the character of str at 10th index
print(s[-10])
OUTPUT
n
y

[Link] College of Commerce (Autonomous), Vijayapur BCA


Programme
UNIT2 FUNCTIONS 20

o
SLICING
String slicing allows us to extract a part of the string. we can specify a start index,
end index, and step size. the general format for slicing is
string[start : end : step]
• start : we provide the starting index.
• end : we provide the end index(this is not included in substring).
• step : it is an optional argument that determines the increment between
each index for slicing.
str = ‘Core Python’
1)str[0:9:1]

Core Pyth
2) str[0:9:2]
Cr yh
3) str[::]
Core Python
4) str[2:4:1]
re
5) str[::2]
Cr yhn
6) str[2::]
re Python
7) str[:4:]
Core
8) str[-4:-1]
tho
9)str[-6: :]
Python

[Link] College of Commerce (Autonomous), Vijayapur BCA


Programme
UNIT2 FUNCTIONS 21

10)str[-1:-4:-1]
noh
11)str[-1::-1]
nohtyp eroC
12)str[-2:2:-1]
ohtyP e

LIST
A list is built-in data structure used to store different collection of items. Lists are:
• Ordered – the items have a defined order.
• Mutable- You can change, add or remove items.
• Indexed- Items can be accessed by their position(index).
• Allow duplicates- the same value can appear more than once.
A LIST IS A SEQUENCE
• Like a string, a list is a sequence of values. In a string, the values are
characters; in a list,They can be any type.
The values in a list are called elements or sometimes items.

• There are several ways to create a new list; the simplest is to enclose the
elements in square brackets ([ and ]):
• []
• [10, 20, 30, 40]
• [‘apple’, ‘orange’, ‘banana’]
• ['spam', 2.0, 5, [10, 20]]
• First example a list that contains no elements is called an empty list; you can
create one with empty brackets, [].The second example is a list of four
integers. the third list of three strings. the elements of a list don’t have to be
the same type. the fourth example list contains a string, a float, an integer,
and another list,a list within another list is nested.

[Link] College of Commerce (Autonomous), Vijayapur BCA


Programme
UNIT2 FUNCTIONS 22

You can assign list values to variables:


>>> cheeses = [‘Alice', ‘Bob', ‘Charles']
>>> numbers = [42, 123]
>>> empty = [ ]
>>> print(cheeses, numbers, empty)
[‘Alice', ‘Bob', ‘Charles'] [42, 123] [ ]
Lists are mutable
• The syntax for accessing the elements of a list is the same as for accessing
the characters
of a string—the bracket operator.
• the expression inside the brackets specifies the [Link] that the
indices start at 0:
>>> cheeses[0]
‘Alice’
• Unlike strings, lists are mutable. when the bracket operator appears on the
left side of an assignment, it identifies the element of the list that will be
assigned.
>>> numbers = [42, 123]
>>> numbers[1] = 5
>>> numbers
[42, 5]
• the one-eth element of numbers, which used to be 123, is now 5.
The in operator also works on lists.
>>> cheeses = [‘Alice', ‘Bob', ‘Charles']
>>> ‘Charles' in cheeses
true
>>> ‘Andrew' in cheeses
false

[Link] College of Commerce (Autonomous), Vijayapur BCA


Programme
UNIT2 FUNCTIONS 23

Traversing a list
• the most common way to traverse the elements of a list is with a for loop.
the syntax is the same as for strings:
for cheese in cheeses:
print(cheese)
This works well if you only need to read the elements of the list. But if you want to
write or update the elements, you need the indices. A common way to do that is to
combine the built-in functions range and len:
for i in range(len(numbers)):
numbers[i] = numbers[i] * 2
This loop traverses the list and updates each element. len returns the number of
elements in the list. range returns a list of indices from 0 to n-1, where n is the
length of the list.
Each time through the loop i gets the index of the next element. The assignment
statement in the body uses i to read the old value of the element and to assign the
new value.

LIST OPERATIONS
• the + operator concatenates lists:
>>> a = [1, 2, 3]
>>> b = [4, 5, 6]
>>> c = a + b
>>> c
[1, 2, 3, 4, 5, 6]
• the * operator repeats a list a given number of times:
>>> [0] * 4
[0, 0, 0, 0]
>>> [1, 2, 3] * 3
[1, 2, 3, 1, 2, 3, 1, 2, 3]

[Link] College of Commerce (Autonomous), Vijayapur BCA


Programme
UNIT2 FUNCTIONS 24

the first example repeats [0] four times. the second example repeats the list [1, 2,
3] three times.
List slices
• the slice operator also works on lists:
>>> t = ['a', 'b', 'c', 'd', 'e', 'f']
>>> t[1:3]
['b', 'c']
>>> t[:4]
['a', 'b', 'c', 'd']
>>> t[3:]
['d', 'e', 'f’]
>>> t[:]
['a', 'b', 'c', 'd', 'e', ‘f’]
if you omit the first index, the slice starts at the beginning. if you omit the second,
the slice goes to the end. so if you omit both, the slice is a copy of the whole list.
• since lists are mutable, it is often useful to make a copy before performing
operations that modify lists.
• a slice operator on the left side of an assignment can update multiple
elements:
>>> t = ['a', 'b', 'c', 'd', 'e', 'f']
>>> t[1:3] = ['x', 'y']
>>> t
['a', 'x', 'y', 'd', 'e', ‘f’]
List methods
python provides methods that operate on lists. for example, append adds a new
element to the end of a list:
>>> t = ['a', 'b', 'c']
>>> [Link]('d')
>>> t
[Link] College of Commerce (Autonomous), Vijayapur BCA
Programme
UNIT2 FUNCTIONS 25

['a', 'b', 'c', 'd']

• extend takes a list as an argument and appends all of the elements:


>>> t1 = ['a', 'b', 'c']
>>> t2 = ['d', 'e']
>>> [Link](t2)
>>> t1
['a', 'b', 'c', 'd', 'e']
• this example leaves t2 unmodified.
• sort arranges the elements of the list from low to high:
>>> t = ['d', 'c', 'e', 'b', 'a']
>>> [Link]()
>>> print(t)
['a', 'b', 'c', 'd', 'e']
sort() changes the list directly and returns None.
to get a new sorted list without changing the original, use sorted():
t = ['d', 'c', 'e', 'b', 'a']
new_list = sorted(t)
print(new_list) # ['a', 'b', 'c', 'd', 'e']
print(t) # ['d', 'c', 'e', 'b', 'a'] (unchanged)
• sort arranges the elements of the list from high to low:
>>> t = ['d', 'c', 'e', 'b', 'a']
>>> [Link](reverse=true)
>>> print(t)
['e’, 'd', ' c', 'b', 'a', ]
Map, filter and reduce
map()

[Link] College of Commerce (Autonomous), Vijayapur BCA


Programme
UNIT2 FUNCTIONS 26

applies a function to each item of a list (or iterable).


Example: square each number
numbers = [1, 2, 3, 4, 5]
squares = list(map(lambda x: x**2, numbers))
print(squares)
output
[1, 4, 9, 16, 25]

filter()
• filters elements of a list based on a condition (true/false).
Example: keep only even numbers
numbers = [1, 2, 3, 4, 5, 6]
evens = list(filter(lambda x: x % 2 == 0, numbers))
print(evens)
Output
[2, 4, 6]

reduce()
repeatedly applies a function to the list elements and reduces them to a single
value. must import from functools:
Example: sum of all numbers
from functools import reduce
numbers = [1, 2, 3, 4, 5]
total = reduce(lambda x, y: x + y, numbers)
print(total)
Output
15

[Link] College of Commerce (Autonomous), Vijayapur BCA


Programme
UNIT2 FUNCTIONS 27

Deleting elements
There are several ways to delete elements from a list. If you know the index of the
element you want, you can use pop:
>>> t = ['a', 'b', 'c']
>>> x = [Link](1)
>>> t
Output
['a', 'c']
>>> x
Output
'b’
• Pop modifies the list and returns the element that was removed.
• If you don’t provide an index, it deletes and returns the last element.

if you don’t need the removed value, you can use the del operator:
>>> t = ['a', 'b', 'c']
>>> del t[1]
>>> t
Output
['a', 'c’]
if you know the element you want to remove (but not the index), you can use
remove:
>>> t = ['a', 'b', 'c']
>>> [Link]('b')
>>> t
Output
['a', 'c']
[Link] College of Commerce (Autonomous), Vijayapur BCA
Programme
UNIT2 FUNCTIONS 28

to remove more than one element, you can use del with a slice index:
>>> t = ['a', 'b', 'c', 'd', 'e', 'f']
>>> del t[1:5]
>>> t
Output
['a', 'f’]
Lists and strings
• A string is a sequence of characters and a list is a sequence of values, but a
list of characters is not the same as a string.
• To convert from a string to a list of characters, you can use list:
Example:
>>> s = 'spam'
>>> t = list(s)
>>> t
Output
['s', 'p', 'a', 'm']
• List is the name of a built-in function, you should avoid using it as a variable
name.
• Avoid l because it looks too much like 1.
• The list function breaks a string into individual letters. if you want to break a
string into words, you can use the split method:
Example:
>>> s = 'pining for the fjords'
>>> t = [Link]()
>>> t
Output:
['pining', 'for', 'the', 'fjords’]
[Link] College of Commerce (Autonomous), Vijayapur BCA
Programme
UNIT2 FUNCTIONS 29

• An optional argument called a delimiter specifies which characters to use


as word boundaries.
• The following example uses a hyphen as a delimiter:
Example:
>>> s = 'spam-spam-spam'
>>> delimiter = '-'
>>> t = [Link](delimiter)
>>> t
Output:
['spam', 'spam', 'spam']
• join is the inverse of split. it takes a list of strings and concatenates the
elements.
• join is a string method, so you have to invoke it on the delimiter and pass the
list as a parameter:
Example:
>>> t = ['pining', 'for', 'the', 'fjords']
>>> delimiter = ' '
>>> s = [Link](t)
>>> s
Output:
'pining for the fjords’
in this case the delimiter is a space character, so join puts a space between
words. To concatenate strings without spaces, you can use the empty string, '', as
a delimiter.
Objects and values
If we run these assignment statements:
a = 'banana'
b = 'banana'

[Link] College of Commerce (Autonomous), Vijayapur BCA


Programme
UNIT2 FUNCTIONS 30

• we know that a and b both refer to a string, but we don’t know whether they
refer to the same string.
• there are two possible states, shown in figure

• In one case, a and b refer to two different objects that have the same value.
• In the second case, they refer to the same object.
• To check whether two variables refer to the same object, you can use the is
operator.
Example:
>>> a = 'banana'
>>> b = 'banana'
>>> a is b
Output:
true
• strings (immutable) → python often reuses the same object for identical
values.
• lists (mutable) → python always creates new objects, even if the contents
are the same.
• String interning in Python
• python optimizes memory by storing only one copy of some immutable
objects (like small strings, numbers, etc.).
• if two variables contain the same string literal, python may reuse the same
object in memory.

• In this example, python only created one string object, and both a and b
refer to it. But when you create two lists, you get two objects:

[Link] College of Commerce (Autonomous), Vijayapur BCA


Programme
UNIT2 FUNCTIONS 31

Example:
>>> a = [1, 2, 3]
>>> b = [1, 2, 3]
>>> a is b
Output:
False

• In this case we would say that the two lists are equivalent, because they
have the same elements, but not identical, because they are not the same
object.
• if two objects are identical, they are also equivalent, but if they are
equivalent, they are not necessarily identical.
• Until now, we have been using “object” and “value” interchangeably, but it is
more precise to say that an object has a value.
• If you evaluate [1, 2, 3], you get a list object whose value is a sequence of
integers.
• If another list has the same elements, we say it has the same value, but it is
not the same object.
Aliasing
• It refers to an object and you assign b = a, then both variables refer to the
same object:
Example:
>>> a = [1, 2, 3]
>>> b = a
>>> b is a
Output:

[Link] College of Commerce (Autonomous), Vijayapur BCA


Programme
UNIT2 FUNCTIONS 32

True
• The association of a variable with an object is called a reference. in this
example, there are two references to the same object.
• An object with more than one reference has more than one name, so we say
that the object is aliased.
• if the aliased object is mutable, changes made with one alias affect the
other:

>>> b[0] = 42
>>> a
[42, 2, 3]
• although this behavior can be useful, it is error-prone. in general, it is safer
to avoid
aliasing when you are working with mutable objects.
• for immutable objects like strings, aliasing is not as much of a problem. in
this example:
a = 'banana'
b = 'banana'
it almost never makes a difference whether a and b refer to the same string or not.
List arguments
when you pass a list to a function, the function gets a reference to the list. if the
function
modifies the list, the caller sees the change. for example, delete_head removes
the first
element from a list:
Example:
def delete_head(t):
[Link] College of Commerce (Autonomous), Vijayapur BCA
Programme
UNIT2 FUNCTIONS 33

del t[0]
here’s how it is used:
>>> letters = ['a', 'b', 'c']
>>> delete_head(letters)
>>> letters
['b', 'c']
the parameter t and the variable letters are aliases for the same object. the stack
diagram
looks like figure 10.5.

• it is important to distinguish between operations that modify lists and


operations that create new lists.
• for example, the append method modifies a list, but the + operator creates a
new list.
• here’s an example using append:

>>> t1 = [1, 2]
>>> t2 = [Link](3)
>>> t1
[1, 2, 3]
>>> t2
None
 The return value from append is none.
 [Link](3) adds 3 to t1.
 But append() returns None, So t2 becomes None.
[Link] College of Commerce (Autonomous), Vijayapur BCA
Programme
UNIT2 FUNCTIONS 34

 If you want t2 to be updated list use t2=t1.

here’s an example using the + operator:


>>> t3 = t1 + [4]
>>> t1
[1, 2, 3]
>>> t3
[1, 2, 3, 4]
• the result of the operator is a new list, and the original list is unchanged.
TUPLES
• A tuple is a built-in data structure in python used to store a collection of
items. Tuples are:
• Ordered – the items have a defined order and that order will not change.
• Immutable – you cannot change, add, or remove items after the tuple is
created.
• Indexed – items can be accessed by their position (index).
• Allow duplicates – the same value can appear more than once.
Tuples are immutable
• A tuple is a sequence of values. the values can be any type, and they are
indexed by integers, so in that respect tuples are a lot like lists.
• The important difference is that tuples are immutable.
• syntactically, a tuple is a comma-separated list of values:
>>> t = 'a', 'b', 'c', 'd', 'e'
• although it is not necessary, it is common to enclose tuples in parentheses:
>>> t = ('a', 'b', 'c', 'd', 'e’)
• to create a tuple with a single element, you have to include a final comma:
>>> t1 = 'a',
>>> type(t1)
[Link] College of Commerce (Autonomous), Vijayapur BCA
Programme
UNIT2 FUNCTIONS 35

<class 'tuple'>
• A value in parentheses is not a tuple:
>>> t2 = ('a')
>>> type(t2)
<class 'str’>
• Another way to create a tuple is the built-in function tuple. with no argument,
it creates an empty tuple:
>>> t = tuple()
>>> t
()
If the argument is a sequence (string, list or tuple), the result is a tuple with the
elements of the sequence:
>>> t = tuple('lupins')
>>> t
('l', 'u', 'p', 'i', 'n', ‘s’)
• each character of the string becomes a separate element in the tuple.
• if you want the whole word "lupins" as one element, you should write:
• t = ('lupins',)
• print(t)
• Because tuple is the name of a built-in function, you should avoid using it as
a variable name.
• most list operators also work on tuples. the bracket operator indexes an
element:
>>> t = ('a', 'b', 'c', 'd', 'e')
>>> t[0]
'a'
• The slice operator selects a range of elements.
>>> t[1:3]

[Link] College of Commerce (Autonomous), Vijayapur BCA


Programme
UNIT2 FUNCTIONS 36

('b', ‘c’)
• But if you try to modify one of the elements of the tuple, you get an error:
>>> t[0] = 'a'
typeerror: object doesn't support item assignment
• Because tuples are immutable, you can’t modify the elements. but you can
replace one tuple with another:
>>> t = ('a',) + t[1:]
>>> t
('a', 'b', 'c', 'd', 'e')
this statement makes a new tuple and then makes t refer to it.
• the relational operators work with tuples and other sequences; python starts
by comparing the first element from each sequence.
• if they are equal, it goes on to the next elements, and so on, until it finds
elements that differ. subsequent elements are not considered (even if they
are really big).
• 1st element same, moves further compares 2nd if finds true further will not be
moved.
>>> (0, 1, 2) < (0, 3, 4)
true
>>> (0, 1, 2000000) < (0, 3, 4)
true

Tuple assignment
• It is often useful to swap the values of two variables. with conventional
assignments, you have to use a temporary variable.
• For example, to swap a and b:
>>> temp = a
>>> a = b
>>> b = temp
[Link] College of Commerce (Autonomous), Vijayapur BCA
Programme
UNIT2 FUNCTIONS 37

• this solution is cumbersome; tuple assignment is more elegant:


>>> a, b = b, a
• The left side is a tuple of variables; the right side is a tuple of expressions.
• each value is assigned to its respective variable.
• the number of variables on the left and the number of values on the right
have to be the same:
>>> a, b = 1, 2, 3
• valueerror: too many values to unpack
• more generally, the right side can be any kind of sequence (string, list or
tuple).
• for example,
to split an email address into a user name and a domain, you could write
>>> addr = 'monty@[Link]'
>>> uname, domain = [Link]('@')
• the return value from split is a list with two elements; the first element is
assigned to uname, the second to domain.
>>> uname
'monty'
>>> domain
'[Link]’

Tuples as return values


• A function can only return one value, but if the value is a tuple, the effect is
the same as returning multiple values.
• for example, if you want to divide two integers and compute the quotient and
remainder, it is inefficient to compute x//y and then x%y.
• It is better to compute them both at the same time.
• The built-in function divmod takes two arguments and returns a tuple of two
values, the Quotient and remainder. You can store the result as a tuple:
[Link] College of Commerce (Autonomous), Vijayapur BCA
Programme
UNIT2 FUNCTIONS 38

>>> t = divmod(7, 3)
>>> t
(2, 1)

• or use tuple assignment to store the elements separately:


>>> quot, rem = divmod(7, 3)
>>> quot
2
>>> rem
1
• here is an example of a function that returns a tuple:
def min_max(t):
return min(t), max(t)
• max and min are built-in functions that find the largest and smallest
elements of a sequence.
• min_max computes both and returns a tuple of two values.

VARIABLE-LENGTH ARGUMENT TUPLES


*args (gathering)
sometimes we don’t know how many arguments a function will get.
if we put * before a parameter name, python will gather all extra arguments into
a tuple.
Example:
def printall(*args):
print(args)
printall(1, 2.0, '3')
Output:
(1, 2.0, '3')
[Link] College of Commerce (Autonomous), Vijayapur BCA
Programme
UNIT2 FUNCTIONS 39

Scatter (unpacking with *)


• The reverse of gather is scatter.
• If we already have a tuple (or list), and we want to pass its values as
separate arguments, we use *.
EXAMPLE:
t = (7, 3) # Directly passing tuple gives error
# divmod(t)
# Unpack the tuple into two separate arguments
print(divmod(*t)) # same as divmod(7, 3)
OUTPUT
(2, 1)
*t tells python: “take elements from the tuple and pass them separately.”

Lists and tuples


• Zip is a built-in function that takes two or more sequences and
interleaves(includes) them. The name Of the function refers to a zipper,
which interleaves two rows of teeth.
Example:
s = 'abc'
t = [0, 1, 2]
for pair in zip(s, t):
print(pair)
Output:
('a', 0)
('b', 1)
('c', 2)

[Link] College of Commerce (Autonomous), Vijayapur BCA


Programme
UNIT2 FUNCTIONS 40

zip pairs elements from two (or more) sequences. a zip object is a kind of
iterator, which is any object that iterates through a sequence.
If you want to use list operators and methods, you can use a zip object to make a
list:
EXAMPLE:
list(zip(s, t))
Output:
[('a', 0), ('b', 1), ('c', 2)]
If the sequences are not the same length, the result has the length of the shorter
one. Zip stops when the shortest sequence ends:
EXAMPLE:
list(zip('Anne', 'Elk’))
Output:
[('A', 'E'), ('n', 'l'), ('n', 'k')]

• you can use tuple assignment in a for loop to traverse a list of tuples:
t = [('a', 0), ('b', 1), ('c', 2)]
for letter, number in t:
print(number, letter)
• each time through the loop, python selects the next tuple in the list and
assigns the elements
to letter and number. the output of this loop is:
OUTPUT
0a
1b
2c

Combining zip + for + tuple assignment

[Link] College of Commerce (Autonomous), Vijayapur BCA


Programme
UNIT2 FUNCTIONS 41

• Check if two sequences have a matching element at the same position:


def has_match(t1, t2):
for x, y in zip(t1, t2):
if x == y:
return True
return False
print(has_match("abc", "adc"))
Output:
True # because at index 0 → 'a' == 'a'

Dictionaries and tuples


dictionaries have a method called items that returns a sequence of tuples,
where each
tuple is a key-value pair.
>>> d = {'a':0, 'b':1, 'c':2}
>>> t = [Link]()
>>> t
dict_items([('c', 2), ('a', 0), ('b', 1)])
• It is an iterator (like a list of tuples).
• we can loop through it:
• for key, value in [Link]():
• print(key, value)
• Output:
• a0
• b1
• c2
• Creating dictionary from list of tuples

[Link] College of Commerce (Autonomous), Vijayapur BCA


Programme
UNIT2 FUNCTIONS 42

• You can make a dictionary from a list of (key, value) tuples:


t = [('a', 0), ('c', 2), ('b', 1)]
d = dict(t)
print(d)
Output:
{'a': 0, 'c': 2, 'b': 1}

Using zip to create dictionary


you can combine zip with dict:
d = dict(zip('abc', range(3)))
print(d)
output:
{'a': 0, 'b': 1, 'c': 2}
'abc' gives keys, range(3) gives values → they get paired.

Updating dictionary with list of tuples


d = {'x': 10}
[Link]([('y', 20), ('z', 30)])
print(d)
Output:
{'x': 10, 'y': 20, 'z': 30}
Tuples as dictionary keys
Lists cannot be keys (because they are mutable), but tuples can.
Example: Telephone directory:
directory = {}
directory['Smith', 'John'] = '555-1234'
directory['Doe', 'Jane'] = '555-5678'

[Link] College of Commerce (Autonomous), Vijayapur BCA


Programme
UNIT2 FUNCTIONS 43

for last, first in directory:


print(first, last, directory[last, first])
Output:
John Smith 555-1234
Jane Doe 555-5678
Here the key is a tuple (last, first).

DICTIONARY
• A dictionary is a built-in python data structure that stores data in key-value
pairs.
• It is like a real-life dictionary: a word (key) maps to its meaning (value).
Properties of Dictionary
• Stores data as key: value pairs.
• Keys must be unique.
• Keys must be immutable (string, number, tuple ).
• Dictionaries are unordered.
• Values can be any type (string, list, number, another dict, etc.).
In mathematical language, a dictionary represents a mapping from keys to
values, so you Can also say that each key “maps to” a value.
Creating An Empty Dictionary
student = dict()
print(student)
Output:
{}
Adding Items
student['one'] = “Alice”
print(student)
Output:
[Link] College of Commerce (Autonomous), Vijayapur BCA
Programme
UNIT2 FUNCTIONS 44

{'one': ‘Alice'}

Creating Dictionary With Items


student = {'one': ‘Alice', 'two': ‘Bob', 'three': ‘Charles'}
print(student)
Output
{'one': ‘Alice’, 'three': ‘Charles', 'two': ‘Bob'}
The order may change, but it doesn’t matter because you always use keys,
not positions.
Accessing values
print(student['two'])
Output
Bob
If key doesn’t exist:
print(student['four’])
Output
KeyError: 'four'

Length:
len(student) # 3

Check if key exists:


'one' in student # True
‘Alice' in student # False (values are not checked)
Check if value exists:
vals = [Link]()
‘Alice' in vals # True

[Link] College of Commerce (Autonomous), Vijayapur BCA


Programme
UNIT2 FUNCTIONS 45

Dictionary as a collection of counters


• Suppose you are given a string and you want to count how many times each
letter appears.
• There are several ways you could do it:
• 26 variables → one for each letter ( messy, not practical).
• List of 26 elements → use ord() to convert character → index (works, but
wastes space if many letters never appear).
• Dictionary → keys = characters, values = counts (best and most flexible).
def histogram(s):
d = dict()
for c in s:
if c not in d:
d[c] = 1 # first time we see this character
else:
d[c] += 1 # already seen → increment
return d
print(histogram('brontosaurus’))
OUTPUT:
{'b': 1, 'r': 2, 'o': 2, 'n': 1, 't': 1, 's': 2, 'a': 1, 'u': 2}
 Dictionaries have a method called get that takes a key and a default value.
 If the key appears in the dictionary, get returns the corresponding value;
otherwise it returns the
Default value.
For example:
>>> h = histogram('a')
>>> h
{'a': 1}
[Link] College of Commerce (Autonomous), Vijayapur BCA
Programme
UNIT2 FUNCTIONS 46

>>> [Link]('a', 0)
1
>>> [Link]('c', 0)
0

Looping and dictionaries


If you use a dictionary in a for statement, it traverses the keys of the dictionary.
def histogram(s):
d = dict()
for c in s:
if c not in d:
d[c] = 1
else:
d[c] += 1
return d
def print_hist(h):
for c in h:
print(c, h[c])
h = histogram('parrot')
print_hist(h)
OUTPUT:
a1
p1
r 2
t1
o1
to traverse the keys in sorted order, you can use the built-in function sorted:

[Link] College of Commerce (Autonomous), Vijayapur BCA


Programme
UNIT2 FUNCTIONS 47

>>> for key in sorted(h):


... print(key, h[key])
a1
o1
p1
r2
t1
Reverse lookup
• Finding key from value
• Now, if you know the value and want the key, it’s not straightforward.
• Why? Because multiple keys can have the same value, and dictionaries are
not optimized for value → key search.
That’s why we need to search manually.
def reverse_lookup_all(d, v):
result = []
for k in d:
if d[k] == v:
[Link](k)
if result:
return result
else:
raise LookupError("Value not found in dictionary")
h = {'a': 1, 'b': 2, 'c': 3, 'd': 2}
print(reverse_lookup_all(h, 2)) # ['b', 'd']

FILES

[Link] College of Commerce (Autonomous), Vijayapur BCA


Programme
UNIT2 FUNCTIONS 48

• Till now, we were taking the input from the console and writing it back to the
console to interact with the user. Instead of that we can able use files as
input or output.
• File is a named location on disk to store related information. It is used to
permanently store data in a non-volatile memory (e.G. Hard disk).
• When we want to read from or write to a file we need to open it first. When
we are done, it needs to be closed, so that resources that are tied with the
file are freed.
• Hence, in python, a file operation takes place in the following order.
 Open a file
 Read or write (perform operation)
 Close the file

OPENING THE FILE MODES: READ,WRITE,APPEND


• This function takes two arguments.
• First is the Filename along with its complete path, and the other Is access
mode.
• This function returns a file object.
Syntax:
Open(filename, mode)
• "r" - read - default value. opens a file for reading, error if the file does not
exist
• "a" - append - opens a file for appending, creates the file if it does not exist
• "w" - write - opens a file for writing, creates the file if it does not exist

READING FROM AND WRITING TO FILES


READ MODE
# Open file in read mode
f = open("[Link]", "r")

[Link] College of Commerce (Autonomous), Vijayapur BCA


Programme
UNIT2 FUNCTIONS 49

# Read the entire content


content = [Link]()
# Print the content
print("File content:")
print(content)
# Close the file
[Link]()

OUTPUT
File content:
python program
Create file with named as [Link] , select file type as text file

WRITE MODE
# Open file in write mode
f = open("[Link]", "w")
# Write some data into the file
[Link]("Hello, this file is opened in write mode.\n")
[Link]("It will overwrite existing content.\n")
# Close the file
[Link]()
print("Data written successfully in write mode.")
OUTPUT
Data written successfully in write mode
• If the file does not exist, it will be created.
• If the file already exists, the old content will be erased/overwritten.

[Link] College of Commerce (Autonomous), Vijayapur BCA


Programme
UNIT2 FUNCTIONS 50

APPEND MODE
# Open file in append mode
f = open("[Link]", "a")
# Append some data
[Link]("This line is added using append mode.\n")
# Close the file
[Link]()
print("Data appended successfully.")
OUTPUT
Data appended successfully

CLOSING FILE
 In python, after finishing file operations, we should close the file to
free up system resources.
 It ensures all data is written (flushed) from memory to the file.
 It frees the file object and resources.

DELETING FILE
import os
# File name
filename = "[Link]"
# Check if file exists before deleting
if [Link](filename):
[Link](filename)
print(f"{filename} deleted successfully.")
else:

[Link] College of Commerce (Autonomous), Vijayapur BCA


Programme
UNIT2 FUNCTIONS 51

print(f"{filename} does not exist.")

OUTPUT:
[Link] deleted successfully
 [Link]() checks if the file is present.
 [Link]() deletes the file.
 if you try to delete a file that doesn’t exist, python will throw an
error → that’s why checking is useful.

[Link] College of Commerce (Autonomous), Vijayapur BCA


Programme

You might also like