0% found this document useful (0 votes)
7 views8 pages

Python Functions, Lists, and Search Techniques

The document is an assignment on Python programming focusing on functions, lists, and search techniques. It covers the definition and creation of functions, types of functions (built-in, user-defined, and anonymous), list operations (creation, accessing, adding, and removing elements), and searching methods (linear and binary search). The assignment is submitted by Vishnu S to Prof. R. Selvam on 12/03/2025.

Uploaded by

yuv5549
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)
7 views8 pages

Python Functions, Lists, and Search Techniques

The document is an assignment on Python programming focusing on functions, lists, and search techniques. It covers the definition and creation of functions, types of functions (built-in, user-defined, and anonymous), list operations (creation, accessing, adding, and removing elements), and searching methods (linear and binary search). The assignment is submitted by Vishnu S to Prof. R. Selvam on 12/03/2025.

Uploaded by

yuv5549
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

PYTHON PROGRAMMING

ASSIGNMENT NO: III


ASSIGNMENT TOPIC: FUNCTIONS, LIST, SEARCH

SUBMITTED TO: Prof. R. SELVAM, MCA., [Link].,


SUBMITTED ON:12/03/2025

SUBMITTED BY:
VISHNU S
2K22BCA347
III-BCA- ‘E’

REFERENCE:

[Link]

[Link]

[Link]
FUNCTIONS IN PYTHON:
A function in Python is a block of code that performs a specific task, and can be
reused. Functions are a fundamental building block of programming.
Syntax:
def function_name(parameters):
# Function body
return value # (optional)

Creating a Function in Python:


When declaring a function in Python, the 'def' keyword must come first, then the
function name, any parameters in parenthesis, and then a colon.
Example:
def greet ():
print('Hello World!')
greet()
Output:
Hello World!
In the above, example we create a simple greet function using def and greet() and
output was ‘Hello World!’.

Calling a Function in Python:


In Python, to call a function, type the function name inside parentheses, and if the
function accepts arguments, add those as well.
Example:
def greet ():
print('Hello World!')
greet()
Output:
Hello World!
In the above example, greet() is used to call the function ‘Hello World!’.
Types of Functions in Python:
Python supports various types of functions, each serving different purposes in
programming. Here are the main types of functions in Python, along with examples:
1. Built-in Functions
2. User-defined Functions
3. Anonymous Functions (Lambda Functions)

1. Built-in Functions:
These functions are pre-defined in Python and can be used directly without any
further declaration.
Example:
# Using the built-in len() function
my_list = [1, 2, 3, 4, 5]
print(len(my_list))
Output:
5.
In the above example, len() function is used to find the length of the list. In the print
statement my_list variable is declared within the len().

2. User-defined Functions:
These are functions that users create to perform specific tasks.
Example:
def add_numbers(a, b):
return a + b
result = add_numbers(3, 5)
print(result)
Output:
8.
In the above example,(a,b) is a user defined which define a values to the variable
within the function(3,5).
3. Anonymous Functions (Lambda Functions):
These are small, unnamed functions defined using the lambda keyword. They are
typically used for short, simple operations.
Example:
x = lamba a, b: a + b
print(x(3,4))
x = lamba a, b: a * b
print(x(3,4))
Output:
7
12.
In the above example, the variable value is declared in the print(x(3,4)) by means
(3,4) is an value of a, b which add(a + b) and multiple(a * b).The lamba function are similar
to the user-defined function but without a name.

LIST IN PYTHON
In Python, lists allow us to store multiple items in a single variable. For example, if
you need to store the ages of all the students in a class, you can do this task using a list.

Create a Python List


We create a list by placing elements inside square brackets [], separated by commas.
For example,
# a list of three elements
ages = [19, 26, 29]
print(ages)
Output:
[19, 26, 29].

Access List Elements


Each element in a list is associated with a number, known as an index. The index of
first item is 0, the index of second item is 1, and so on.
Example:
languages = ['Python', 'Swift', 'C++']
print('languages[0] =', languages[0])
print('languages[2] =', languages[2])
Output:
languages[0] = Python
languages[2] = C++.
The above example, expressed that the list elements were accessed by index position.

Adding Elements into List


We can add elements to a list using the following methods:
 append(): Adds an element at the end of the list.
 extend(): Adds multiple elements to the end of the list.
 insert(): Adds an element at a specific position.

Example:
a = []
# Adding
[Link](10)
print("After append(10):", a)
# Inserting
[Link](0, 5)
print("After insert(0, 5):", a)
# Extend
[Link]([15, 20, 25])
print("After extend([15, 20, 25]):", a)
Output:
After append(10): [10]
After insert(0, 5): [5, 10]
After extend([15, 20, 25]): [5, 10, 15, 20, 25]
The above example show the some list function like append, insert, extend which
append used to add the element(10) in the list, insert function used to insert the element(5) in
the 0th position in the list and extend function used to add more element in the list in sequence
order.
Removing Elements from List
We can remove elements from a list using:
 remove(): Removes the first occurrence of an element.
 pop(): Removes the element at a specific index or the last element if no index is
specified.
 del function: Deletes an element at a specified index.

Example:
a = [10, 20, 30, 40, 50]
# Removes
[Link](30)
print("After remove(30):", a)
#Pop
popped_val = [Link](1)
print("Popped element:", popped_val)
print("After pop(1):", a)
# Deletes
del a[0]
print("After del a[0]:", a)
Output:
After remove(30): [10, 20, 40, 50]
Popped element: 20
After pop(1): [10, 40, 50]
After del a[0]: [40, 50]
The above example show that some remove function from the list like remove, pop
and del. remove function completely remove the particular element(30) from the list, pop
function used to delete the element by their index position and del statement also like pop
which delete the element by their index position.

SEARCH IN PYTHON
Search is a fundamental techniques used to find an element or a value within a
collection of data.
Types of Search
[Link] Search
[Link] Search
[Link] Search:
Linear search is the simplest searching technique. It sequentially checks each element
of the list until it finds the target value.
Example:
List1 = [1,2,3,4,5,6]
Search = int(input(“Enter a number:”))
For i in range (0, len(list1)):
if search == list[i]:
print(i)
Output:
Enter a number:4
3.
In the example, search the element one by one in the given array which resulted the
index position of element.

2. Binary Search:
Binary search is a more efficient searching technique suitable for sorted lists. It
repeatedly divides the search interval in half until the target value is found.
Example:
def binary(array, x, low, high):
while low <= high:
mid = low+(high-low)//2
if x == array[mid]:
return mid
elif x > array [mid]:
low = mid + 1
else:
high = mid – 1
return -1
array = [3,4,5,6,7,8,9]
x=4
result = binary(array, x, 0, len(array)-1)
if result! =-1:
print(“Element is present at index”+str(result))
else:
print(“Not found”)
Output:
Element is present at index:6.

In the above example, first it will divide the given array into two half to find the mid
element, after the element are compared equal to the mid if, that element is equal it result the
output otherwise it compare the element to high or low then repeat the process of finding the
middle element.

Common questions

Powered by AI

The primary difference between linear search and binary search lies in their execution method and efficiency. Linear search checks each element sequentially from the list until it finds the target value, making it straightforward but less efficient for large datasets. Conversely, binary search utilizes a divide-and-conquer approach where it divides the sorted list into halves to find the target element, significantly reducing the search interval with each step, thus leading to faster search times in sorted lists .

Python's built-in functions provide the advantages of simplicity and optimized performance, as they are pre-defined in the language and implemented efficiently. They streamline coding by eliminating the need for function definitions for common operations, ensuring standardization and error minimization through tested code. Conversely, user-defined functions are tailored to specific needs but require more time for definition and may not match the performance optimization of built-in implementations .

Anonymous functions, particularly lambda functions, are favored in Python for their ability to perform simple, quick operations without the need for a named declaration, promoting concise and cleaner code in scenarios requiring short-lived or one-off function definitions. They enforce functional programming principles and are usually used as arguments to higher-order functions like 'map', 'filter', and 'reduce'. However, their single-expression limitation and scope restriction can be a drawback when complex or multi-statement logic is necessary .

When choosing between 'pop()' and 'remove()', it is crucial to consider the desired operation: 'pop()' is used to remove an element based on its index, returning the element, which is useful when the position is known or when needing to retrieve the element. 'remove()' deletes the first occurrence of a value, useful when only the value matters and its index is unknown. Additionally, 'pop()' affects time efficiency since indexing in lists is O(1), while finding a specific value with 'remove()' is O(n) due to the search .

The 'extend()' method in Python allows adding multiple elements to the end of a list by iterating over its argument and adding each element one by one, effectively concatenating the argument to the list. In contrast, the 'append()' method adds its argument as a single element, increasing the list's nested dimension if the argument is a list. Thus, 'extend()' is used for list-to-list appending of multiple elements, while 'append()' is for adding a single item .

Indexing in a Python list assigns a numerical position to each element starting from zero, enabling efficient and direct access or modification of elements based on their positional reference. This systematic approach is crucial for operations involving retrieval, updates, and slicing, as it allows precise control and rapid access—essential for iteration and operations requiring specific element handling. Proper indexing is central to list manipulation and enhances code efficiency and clarity .

A binary search is significantly preferable over a linear search in scenarios involving large datasets where efficiency is critical and the list is sorted. Its logarithmic time complexity allows operations on large data with fewer comparisons, greatly optimizing performance compared to the linear search's linear time complexity. Preconditions for employing a binary search include ensuring the list is sorted, as the algorithm's efficiency hinges on dividing a sorted interval, making it unsuitable for unsorted lists where linear search is more appropriate despite lower efficiency .

The 'insert()' function in a Python list allows the addition of an element at a specified index, shifting existing elements to accommodate the new entry. This contrasts with 'append()', which adds an element to the list’s end, and 'extend()', which adds multiple elements to the end. 'insert()' is thus more precise for positioning elements, but might affect performance by needing to shift subsequent elements, while 'append()' and 'extend()' preserve order and require less structural adjustment .

The 'remove()' method in Python lists deletes the first occurrence of a specified value, whereas 'del' removes an item at a specified index. 'remove()' is useful when the value is known but not its position, making it suitable when the goal is to ensure an element is not in the list. Meanwhile, 'del' is optimal when the specific position is important, such as when altering list structure based on indices or needing to delete a slice. Each method provides distinctive strategies based on the nature of the list elements and the requirement for position .

Lambda functions in Python are defined using the 'lambda' keyword and do not require a formal 'def' declaration or a name, unlike regular user-defined functions. They are typically used for short, simple operations that are constructed in a single line, whereas user-defined functions are used for more complex operations that may span multiple lines and may require a name for reuse and clarity .

You might also like