II Year I Semester - Python
Programming
(Skill Enhancement Course)
UNIT-II
Function in Python
A function in Python is a block
of organized, reusable code that performs a specific task. Functions help break
down large programs into smaller, manageable, and modular chunks, improving
readability and re-usability.
Python Function Declaration
The syntax to declare a function
is:
Types of Functions in Python
Below are the different types of functions in Python:
·
Built-in
library function: These are Standard
functions in Python that are available to use.
· User-defined function: We can create our own functions
based on our requirements.
Built-in functions
in Python are a set of pre-defined functions that are readily available for use
without needing to import any modules. These functions provide fundamental
functionalities for various tasks, including data type manipulation,
input/output operations, and working with iterables.
Some commonly used built-in
functions include:
- print(): Displays output to the console.
- len(): Returns the length (number of items) of an object, such as a
string, list, or tuple.
- input(): Allows the user to enter input from the console.
- int(), float(), str(): Used for type conversion between integers,
floating-point numbers, and strings.
- abs(): Returns the absolute value of a number.
- sum(): Calculates the sum of all items in an iterable.
- min(), max(): Return the minimum and maximum values from an iterable or set of
arguments.
- range(): Generates a sequence of numbers.
- list(), tuple(), dict(), set(): Used to create instances of these collection
data types.
- sorted(): Returns a new sorted list from the items in an iterable.
- enumerate(): Adds a counter to an iterable, returning an enumerate object.
- zip(): Combines multiple iterables into an iterator of tuples.
These are just a few examples,
and Python offers a comprehensive set of built-in functions to streamline
various programming tasks.
Calling a Function
To call a function
in Python, we definitely type the name of the function observed via parentheses
(). If the function takes any arguments, they may be covered within the
parentheses. Below is the example for calling def function Python.
Syntax of Calling a function:
def fun():
print("")
#calling a function
fun()
# Defining a function with
parameters
def greet(name, age):
print(name, age)
#calling a function by passing arguments
greet("Alice",21)
OUT PUT:
Welcome
to GFG
Alice
21
·
Calling
fun(): The function
fun() is called without any arguments, and it prints "Welcome to
GFG".
· Calling greet("Alice",
21): The function
greet() is called with the arguments "Alice" and 21, which are
printed as "Alice 21".
The Python return
statement marks the end of a function and specifies the value or values to pass
back from the function. Return statements can return data of any type,
including integers, floats, strings, lists, dictionaries, and even other
functions. If no return statement is used, or if a return statement is used
without a value, the function will implicitly return None.
Type
Conversion in Python
Type conversion means changing one data type
into another.There are two types:
1.
Implicit Type Conversion (Type
Casting by Python):
Also called Type Casting done automatically by Python. Python
converts smaller data types into larger data types to avoid data loss.
CODE:
# Implicit Type Conversion
x = 10
# int
y = 3.5
# float
result = x + y # int + float = float
print("x:", x,
"type:", type(x))
print("y:", y,
"type:", type(y))
print("result:",
result, "type:", type(result))
OUPUT:
x: 10 type: <class 'int'>
y: 3.5 type: <class 'float'>
result: 13.5 type: <class 'float'>
->Here, Python automatically converted int (10) to float (10.0) before addition.
2. Explicit Type
Conversion (Type Casting by User): Also
called Type Casting done manually using functions like:
1. int()
2. float()
3. str()
4. list()
5. tuple()
6. set()
CODE:
# Explicit Type Conversion
a = "100" #
string
b = "25"
# string
# Convert
string to int
sum_result = int(a) + int(b)
# Convert
int to string
concat_result = str(a) + str(b)
print("Sum:",
sum_result, "type:", type(sum_result))
print("Concatenation:",
concat_result, "type:", type(concat_result))
OUTPUT:
Sum: 125 type: <class 'int'>
Concatenation: 10025 type: <class 'str'>
Here:
·
"100" and "25" were strings.
·
We used int() to convert them into integers for arithmetic.
·
We used str() to join them as strings
Implicit Conversion → Python decides (automatic).
Explicit Conversion → Programmer decides (manual,
using functions).
The
return statement in Python has two primary purposes:
·
It immediately exits a function.
·
It sends a value back to where the function was called.
Any code inside a function after a return statement is executed
will not run. If a function doesn't have an explicit return statement, it
automatically returns the special value None.
Syntax:
return [value]
CODE:
Example
1: # A function that calculates and
returns a value
def add(a, b):
result = a + b
return result
OUTPUT:
None
Example
2: # The value returned from the function is stored in a variable
sum_value = add(5, 3)
print(sum_value)
OUTPUT:
8
How to Use the Return Statement in Python
In Python, the return statement exits a function and passes back
a value to the function call. Here's the basic syntax for using return
statements:
def function_name(parameter1, parameter2):
# Function body
return return_value
·
def: The keyword to start the function definition.
·
function_name: A unique identifier to name the function.
·
parameter(s): Any number of variables listed inside the
parentheses help pass data into the function (optional).
·
return: The keyword to exit the function before reaching its end
(optional).
·
return_value: A value or variable to return from the function
(optional).
Functions can also include lambda expressions when compact,
anonymous functions are necessary for quick operations. Functions in Python are
highly versatile, allowing programmers to use complex logic while keeping the
code modular and efficient.
When to Use the Return
Statement in Python
The return statement is useful for returning the result of a
calculation or retrieving specific data. Another use case for a return
statement is exiting a function based on conditions.
Sending Back Results
A return statement is essential whenever you want to send the
result of a function back to where you called the function.
CODE:
def calculate_area(length, width):
area = length * width
return area
area = calculate_area(50, 50) # get the result of the function
print(f"Calculated area: {area}") # use the result of the
function
OUTPUT:
Calculated area: 2500
->The return
keyword in Python enables the function to send results back to its caller.
Python Keyword Arguments
Keyword Arguments, You can also send arguments with the key
= value syntax.
This way the order of the arguments does not matter.
CODE:
def
my_function(child3, child2, child1):
print("The
youngest child is " + child3)
my_function(child1
= "Emil", child2 = "Tobias", child3 = "Linus")
OUTPUT:
The
youngest child is Linus
Introduction to *args and **kwargs in Python
In Python, we can pass a variable number of arguments to a
function using special symbols. There are two special symbols:
1.
*args (Non Keyword Arguments)
2. **kwargs (Keyword
Arguments)
We use *args and **kwargs as an argument when we are unsure about
the number of arguments to pass in the functions.
Python *args (Arbitrary
Positional Arguments)
·
The *args syntax allows a function to accept an arbitrary number
of non-keyworded (positional) arguments.
·
When *args is used in a function definition, all the positional
arguments passed to the function are collected into a tuple.
·
The name args is a convention; you could use any valid variable
name preceded by a single asterisk (e.g., *numbers, *items).
CODE:
def sum_all(*numbers):
total = 0
for num in numbers:
total += num
return total
print(sum_all(1, 2, 3)) # Output: 6
print(sum_all(5, 10, 15, 20)) # Output: 50
·
As in the above example we are not sure about the number of
arguments that can be passed to a function. Python has *args which allow us to
pass the variable number of non keyword arguments to function.
·
In the function, we should use an asterisk * before the parameter
name to pass variable length arguments.The arguments are passed as a tuple and these
passed arguments make tuple inside the function with same name as the parameter
excluding asterisk *.
Example 2: Using *args to pass the
variable length arguments to the function
CODE:
def
adder(*num):
sum = 0
for n in num:
sum = sum + n
print("Sum:",sum)
adder(3,5)
adder(4,5,6,7)
adder(1,2,3,5,6)
OUTPUT:
Sum: 8
Sum: 22
Sum: 17
In the
above program, we used *num as a parameter which allows us to pass variable
length argument lists to the adder () function. Inside the function, we have a
loop which adds the passed argument and prints the result. We passed 3
different tuples with variable length as an argument to the function.
Python **kwargs
(Arbitrary Keyword Arguments)
·
The **kwargs syntax allows a function to accept an arbitrary
number of keyworded arguments.
·
When **kwargs is used in a function definition, all the keyword
arguments passed to the function are collected into a dictionary.
·
The name kwargs is a convention; you could use any valid variable
name preceded by a double asterisk (e.g., **options, **data).
CODE:
def display_info(**details):
for key, value in details.items():
print(f"{key}: {value}")
display_info(name="Alice", age=30,
city="New York")
OUTPUT:
name:
Alice
age: 30
city: New
York
Combining *args and **kwargs
·
You can use both *args and **kwargs in the same function
definition.
·
When combining them, *args must come before **kwargs in the
function signature.
CODE:
def
process_data(fixed_arg, *args, **kwargs):
print(f"Fixed
argument: {fixed_arg}")
print(f"Positional
arguments: {args}")
print(f"Keyword
arguments: {kwargs}")
process_data("Start",
1, 2, 3, item1="Apple", item2="Banana")
OUTPUT:
Fixed argument: Start
Positional arguments: (1, 2, 3)
Keyword arguments: {'item1': 'Apple', 'item2': 'Banana'}
· Python
passes variable length non keyword argument to function using *args but we
cannot use this to pass keyword arguments. For this problem Python has got a
solution called **kwargs, it allows us to pass the variable length of keyword
arguments to the function.
· In the
function, we use the double asterisk ** before the parameter name to denote
this type of argument. The arguments are passed as a dictionary and these
arguments make a dictionary inside function with name same as the parameter
excluding double asterisk **.
Example: Using **kwargs to pass the variable keyword arguments to
the function
CODE:
def intro(**data):
print("\nData type
of argument:",type(data))
for key, value in
data.items():
print("{}
is {}".format(key,value))
intro(Firstname="Sita",
Lastname="Sharma", Age=22, Phone=1234567890)
intro(Firstname="John",
Lastname="Wood", Email="johnwood@nomail.com",
Country="Wakanda", Age=25, Phone=9876543210)
OUTPUT:
Data type
of argument: <class 'dict'>
Firstname
is Sita
Lastname
is Sharma
Age is 22
Phone is
1234567890
Data type
of argument: <class 'dict'>
First
name is John
Last name
is Wood
Email is
johnwood@nomail.com
Country
is Wakanda
Age is 25
Phone is
9876543210
In the
above program, we have a function intro() with **data as a parameter. We passed
two dictionaries with variable argument length to the intro() function. We have
a for loop inside the intro() function which works on the data of the passed
dictionary and prints the value of the dictionary.
String in Python
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 a
single character is a string of length 1.
CODE:
s = "dear students"
print(s[1]) # access 2nd char
s1 = s + s[0] # update
print(s1) # print
OUTPUT:
e
dear studnetsd
Creating a String:
Strings can be created using either
single (') or double (") quotes.
CODE:
s1 = 'The beautiful thing about learning is that
no one can take it away from you'
s2 = "An investment in knowledge pays the
best interest."
print(s1)
print(s2)
OUTPUT:
The beautiful thing
about learning is that no one can take it away from you
An investment in
knowledge pays the best interest.
Multi-line Strings:
If we need a string to span multiple lines then we can use triple quotes (''' or """).
CODE:
Python String on
interestingly"""
print(s)
s = '''I'm a
good student'''
print(s)
OUTPUT:
I am Learning
Python String on
interestingly
I'm
a good student
Strings in Python are sequences
of characters, so we can access individual characters using indexing. Strings
are indexed starting from 0 and -1 from end. This allows
us to retrieve specific characters from the string.
CODE:
# Accesses first
character: 'G'
print(s[0])
# Accesses 5th
character: 's'
print(s[4])
OUTPUT:
S
Note: Accessing an
index out of range will cause an IndexError. Only integers are allowed
as indices and using a float or other types will result in a TypeError.
Access
string with Negative Indexing:
Python allows negative address references to access characters from the back of the String, e.g. -1 refers to the last character, -2 refers to the second last character, and so on.
CODE:
s =
"GeeksforGeeks"
# Accesses 3rd
character: 'k'
print(s[-10])
# Accesses 5th
character from end: 'G'
print(s[-5])
OUTPUT:
k
G
String Slicing:
CODE:
s = "Hi students
hope all are doing good"
print(s[1:4])
print(s[:3])
print(s[3:])
# Reverse a string
print(s[::-1])
OUTPUT:
i
s
Hi
students
hope all are doing good
doog
gniod era lla epoh stneduts iH
Deleting a
String:
In Python, it is
not possible to delete individual characters from a string since strings are
immutable. However, we can delete an entire string variable using the del keyword.
CODE:
s =
"GfG"
# Deletes entire string
del s
OUTPUT:
NONE
Updating a
String:
To update a part
of a string we need to create a new string since strings are immutable.
CODE:
s = "Dear
students"
s2 =
s.replace("students", "CSE A and B Students")
print(s2)
OUTPUT:
Dear
CSE A and B Students
Python String Formatting:
F-String was
introduced in Python 3.6, and is now the preferred way of formatting strings.
Before Python 3.6 we had to use the format() method.
F-Strings
- F-string allows you to format selected parts of a string.
- To specify a string as an
f-string, simply put an f in front of the string
literal, like this:
Create an f-string:
CODE:
txt = f"The price of a
book is 49 dollars"
print(txt)
OUTPUT:
The price of a
book is 49 dollars
Placeholders and Modifiers:
To format values in an f-string, add
placeholders {}, a placeholder
can contain variables, operations, functions, and modifiers to format the
value.
Add a
placeholder for the price variable:
CODE:
txt = f"The price
of two books {price} dollars"
print(txt)
OUTPUT:
Perform Operations in F-Strings:
You can perform Python operations inside the placeholders and You can do math operations:
CODE:
txt = f"The price for 20 books {20 * 50}
dollars"
print(txt)
OUTPUT:
The price for 20 books 1000
dollars
You can perform
math operations on variables:
CODE:
price = 59
tax = 0.25
txt = f"The price is
{price + (price * tax)} dollars"
print(txt)
OUTPUT:
The price is
73.75 dollars
Multiple Values
If you want to use more values, just add
more values to the format() method:
print(txt.format(price, itemno,
count))
CODE:
quantity = 3
itemno = 567
price = 49
myorder = "I want
{} pieces of item number {} for {:.2f} dollars."
print(myorder.format(quantity,
itemno, price))
OUTPUT:
I want 3 pieces of
item number 567 for 49.00 dollars.
Python Lists
Lists are used to store multiple
items in a single variable.
Lists are one of 4 built-in data
types in Python used to store collections of data, the other 3 are Tuple, Set, and Dictionary, all with different qualities
and usage.
Lists are created using square
brackets:
mylist = ["apple", "banana", "cherry"]
Create a List:
CODE:
thislist =
["apple", "banana", "cherry"]
print(thislist)
OUTPUT:
['apple',
'banana', 'cherry']
To determine how many items a
list has, use the len() function:
Print the number
of items in the list:
CODE:
thislist =
["apple", "banana", "cherry"]
print(len(thislist))
OUTPUT:
3
List Items - Data Types:
List items can be of any data type. Here an Example Program
for String, int and boolean data types.
CODE:
list1 = ["apple",
"banana", "cherry"]
list2 = [1, 5, 7, 9, 3]
list3 = [True, False,
False]
print(list1)
print(list2)
print(list3)
OUTPUT:
['apple', 'banana', 'cherry']
[1, 5, 7, 9, 3]
[True, False, False]
Python Collections (Arrays):
There are four collection data types in the Python programming language:
- List is a
collection which is ordered and changeable. Allows duplicate members.
- Tuple is a
collection which is ordered and unchangeable. Allows duplicate members.
- Set is a collection
which is unordered, unchangeable*, and unindexed. No duplicate members.
- Dictionary is a collection which is ordered** and changeable. No
duplicate members.
Access Items:
List items are indexed and you can access them by referring to the index
number and here an Example
to print the second item of the list:
CODE:
thislist =
["apple", "banana", "cherry"]
print(thislist[1])
OUTPUT:
banana
Check if Item Exists:
To determine if a specified item is present in a list use the in keyword. Here an Example
to check if "apple" is
present in the list:
CODE:
thislist =
["apple", "banana", "cherry"]
if "apple" in
thislist:
print("Yes,
'apple' is in the fruits list")
OUTPUT:
Yes, 'apple' is
in the fruits list
Change a Range of Item Values:
To change the
value of items within a specific range, define a list with the new values, and
refer to the range of index numbers where you want to insert the new values,
here an Example to Change the values
"banana" and "cherry" with the values
"blackcurrant" and "watermelon":
CODE:
thislist =
["apple", "banana", "cherry", "orange",
"kiwi", "mango"]
thislist[1:3] =
["blackcurrant", "watermelon"]
print(thislist)
OUTPUT:
['apple', 'blackcurrant',
'watermelon', 'orange', 'kiwi', 'mango']
Remove Specified
Item:
The remove() method removes the specified item. Here an Example to remove "banana":
CODE:
thislist =
["apple", "banana", "cherry"]
thislist.remove("banana")
print(thislist)
OUTPUT:
['apple',
'cherry']
Extend List:
To append elements from another list to the current list, use the extend() method.
Example to Add the elements of tropical to thislist:
CODE:
thislist =
["apple", "banana", "cherry"]
tropical =
["mango", "pineapple", "papaya"]
thislist.extend(tropical)
print(thislist)
OUTPUT:
['apple', 'banana', 'cherry',
'mango', 'pineapple', 'papaya']
Remove Specified Item:
The remove() method removes the specified item. Here an Example to Remove "banana":
CODE:
thislist =
["apple", "banana", "cherry"]
thislist.remove("banana")
print(thislist)
OUTPUT:
['apple', 'cherry']
Remove Specified Index:
The pop() method removes the specified index. Here an Example Remove the second item:
CODE:
thislist =
["apple", "banana", "cherry"]
thislist.pop(1)
print(thislist)
OUTPUT:
['apple', 'cherry']
Loop Through a List:
You can
loop through the list items by using a for loop. Here an
Example Print all items in the list, one by one:
CODE:
thislist
= ["apple", "banana", "cherry"]
for x
in thislist:
print(x)
apple
banana
cherry
Loop Through the Index Numbers:
You can also loop through the list items by
referring to their index number.
Use the range() and len() functions to create a suitable iterable. Here an
Example to Print all items by referring to their index
number:
CODE:
thislist =
["apple", "banana", "cherry"]
for i in
range(len(thislist)):
print(thislist[i])
OUTPUT:
apple
banana
cherry
List Comprehension:
·
List
comprehension offers a shorter syntax when you want to create a new list based
on the values of an existing list.
·
Example:
·
Based
on a list of fruits, you want a new list, containing only the fruits with the
letter "a" in the name.
·
Without
list comprehension you will have to write a for statement with
a conditional test inside:
CODE:
fruits =
["apple", "banana", "cherry", "kiwi",
"mango"]
newlist = []
for x in fruits:
if "a" in x:
newlist.append(x)
print(newlist)
OUTPUT:
['apple', 'banana', 'mango']
Sort List Alphanumerically:
List objects have a sort() method that will sort the list alphanumerically, ascending, by default. Here
an Example
to Sort the list alphabetically.
CODE:
thislist =
["orange", "mango", "kiwi",
"pineapple", "banana"]
thislist.sort()
print(thislist)
OUTPUT:
['banana', 'kiwi', 'mango',
'orange', 'pineapple']
WEEK – II Programs
1) Write a program
to define a function with multiple return values
Return values using comma
def name():
return
"Richard","Kewin"
# print the tuple with the returned values
print(name())
# get the individual items
name_1, name_2 = name()
print(name_1, name_2)
OUTPUT:-
--------- Try on your own👏------------------------------
Using a dictionary
CODE:
def name():
n1 = "Richard"
n2 = "Kelwin"
return {1:n1, 2:n2}
names = name()
print(names)
OUTPUT:-
2) Write a program
to define a function using default arguments
Python Function Arguments:
CODE:
def add_numbers(a, b):
sum = a + b
print('Sum:', sum)
add_numbers(2, 3)
OUTPUT:-
--------- Try on your own👏------------------------------
Function Argument with Default Values:
CODE:
def add_numbers( a = 7, b = 8):
sum = a + b
print('Sum:', sum)
# function call with two arguments
add_numbers(2, 3)
# function call with one argument
add_numbers(a = 2)
# function call with no arguments
add_numbers()
OUTPUT:-
--------- Try on your own👏------------------------------
Exp: Here, we have
provided default values 7 and 8 for parameters a and b respectively. Here's how
this program works
1. add_numbers(2, 3)
Both values are
passed during the function call. Hence, these values are used instead of the
default values.
2. add_numbers(2)
Only one value is
passed during the function call. So, according to the positional argument 2 is
assigned to argument a, and the default value is used for parameter b.
3. add_numbers()
No value is passed
during the function call. Hence, default value is used for both parameters a
and b.
Python Keyword Argument:
CODE:
def display_info(first_name, last_name):
print('First Name:',
first_name)
print('Last Name:',
last_name)
display_info(last_name = 'leo', first_name =
'joy')
OUTPUT:-
--------- Try on your own👏------------------------------
Exp: Hence,
first_name in the function call is assigned to first_name in the function
definition. Similarly, last_name in the function call is assigned to last_name
in the function definition.
In such scenarios,
the position of arguments doesn't matter.
3) Write a
program to find the length of a string without using the library function in
python
CODE:
my_string = "Hi students"
print("The string is :")
print(my_string)
my_count=0
for i in my_string:
my_count=my_count+1
print("The length of the string is ")
print(my_count)
OUTPUT:-
--------- Try on your own👏------------------------------
4) Write a program
to check if the substring is present in a given string or not
Check Python Substring in String using the If-Else
# Take input from users
my_string = "I am a good student and i will
execute all the programs in python"
if "I am A " in my_string:
print("Yes! it is
present in the string")
else:
print("No! it is not
present")
OUTPUT:-
--------- Try on your own👏------------------------------
Check Python Substring in String using Find() method
CODE:
def check(string, sub_str):
if (string.find(sub_str)
== -1):
print("NO")
else:
print("YES")
string = "Be a good student"
sub_str = "of"
check(string, sub_str)
OUTPUT:-
--------- Try on your own👏------------------------------
5) write a program
to perform the given operations on a list a) Addition b) Insertion c)
slicing
a)Addition :
Using the "+" Operator
CODE:
b = 12
# Adding two numbers
res = a + b
print(res)
OUTPUT:-
--------- Try on your own👏------------------------------
Using user input
CODE:
# taking user input
a = input("First number: ")
b = input("Second number: ")
# converting input to float and adding
res = float(a) + float(b)
print(res)
OUTPUT:-
--------- Try on your own👏------------------------------
Using Function
CODE:
# creating a list
fruit =
["banana","cherry","mango","grape"]
fruit.insert(1,"kiwi")
print(fruit)
OUTPUT:-
--------- Try on your own👏------------------------------
# function to add two numbers
def add(a, b):
return a + b
# initializing numbers
a = 10
b = 5
# calling function
res = add(a,b)
print(res)
OUTPUT:-
--------- Try on your own👏------------------------------
b)Insertion: Python List insert() method inserts an item at a specific index in a list.
CODE:
list1 = [ 1, 2, 3, 4, 5, 6, 7 ]
# insert 10 at 4th index
list1.insert(4, 10)
print(list1)
OUTPUT:-
--------- Try on your own👏------------------------------
Insertion in a List Before any Element:
CODE:
# Python3 program for Insertion in a
list
# before any element using insert() method
list1 = [ 1, 2, 3, 4, 5, 6 ]
# Element to be inserted
element = 13
# Element to be inserted before 3
beforeElement = 3
# Find index
index = list1.index(beforeElement)
# Insert element at beforeElement
list1.insert(index, element)
print(list1)
OUTPUT:-
--------- Try on your own👏------------------------------
c) Slicing: Retrieve All Characters
CODE:
# Get the entire string
s2 = s[:]
s3 = s[::]
s4 = s [:]
print(s2)
print(s3)
print(s4)
OUTPUT:-
--------- Try on your own👏------------------------------
Get All Characters Before or After a Specific Position:
CODE:
s =
"Hello, Students hope all are fine"
# Characters from index 7 to the end
print(s[6:])
# Characters from the start up to index 5
(exclusive)
print(s[:5])
OUTPUT:-
--------- Try on your own👏------------------------------
6) Write a program
to perform any 5 built-in functions in python
Demonstrating 5 simple built-in functions:
CODE:
# 1. len() - returns the length of an object
my_list = [10, 20, 30, 40, 50]
print("Length of the list:",
len(my_list))
# 2. sum() - sums the items of an iterable
print("Sum of the list elements:",
sum(my_list))
# 3. max() - returns the largest item in an
iterable
print("Maximum element in the list:",
max(my_list))
# 4. min() - returns the smallest item in an
iterable
print("Minimum element in the list:",
min(my_list))
# 5. abs() - returns the absolute value of a
number
negative_number = -100
print("Absolute value of -100:",
abs(negative_number))
OUTPUT:-
--------- Try on your own👏------------------------------
Demonstrating 5 more built-in functions:
# 1. enumerate() - adds a counter to an iterable
my_list = ['apple', 'banana', 'cherry']
print("Using enumerate():")
for index, value in enumerate(my_list):
print(f"Index:
{index}, Value: {value}")
# 2. zip() - combines multiple iterables
list1 = [1, 2, 3]
list2 = ['a', 'b', 'c']
print("\nUsing zip():")
for item1, item2 in zip(list1, list2):
print(item1, item2)
# 3. map() - applies a function to all items in an
input list
def square(x):
return x * x
numbers = [1, 2, 3, 4, 5]
squared_numbers = list(map(square, numbers))
print("\nUsing map():", squared_numbers)
# 4. filter() - constructs an iterator from
elements of an iterable for which a function returns true
def is_even(x):
return x % 2 == 0
even_numbers = list(filter(is_even, numbers))
print("Using filter():", even_numbers)
# 5. reduce() - applies a function of two
arguments cumulatively to the items of a sequence (requires import)
from functools import reduce
def add(x, y):
return x + y
sum_of_numbers = reduce(add, numbers)
print("Using reduce():", sum_of_numbers)
OUTPUT:-
--------- Try on your own👏------------------------------