Page 522 - ComputerScience_Class_11
P. 522
Output
The number is: Odd
FUNCTIONS WITH LIST, TUPLE AND DICTIONARY
Functions can work with various data types, including lists, tuples and dictionaries. Understanding how to pass and
manipulate these data types within functions is essential for writing effective and efficient Python code. Lists and
dictionaries are mutable and can be modified, while tuples are immutable, meaning their values cannot be changed
after creation. This section explores how functions interact with these data types, including how to pass them as
arguments and modify them where possible.
Functions with Lists
Lists are mutable, they can be modified inside a function. You can pass a list to a function and any changes made to the
list within the function will affect the original list.
Program 8: Write a program to modify a list by adding an element inside a function.
Program 8.py
File Edit Format Run Options Window Help
def add_to_list(my_list):
my_list.append(5)
numbers = [1, 2, 3, 4]
Output
add_to_list(numbers)
print("Modified list:", numbers) Modified list: [1, 2, 3, 4, 5]
Functions with Tuples
Tuples are immutable, which means that their values cannot be modified after they are created. However, you can
work with tuples inside functions by creating new tuples based on the existing ones or returning a modified tuple.
Program 9: Write a program to add an element to a tuple inside a function by creating a new tuple.
Program 9.py
File Edit Format Run Options Window Help
def add_to_tuple(my_tuple):
new_tuple = my_tuple + (6,)
return new_tuple
numbers_tuple = (1, 2, 3, 4)
Output
modified_tuple = add_to_tuple(numbers_tuple)
print("Modified tuple:", modified_tuple) Modified tuple: (1, 2, 3, 4, 6)
Functions with Dictionaries
Dictionaries are mutable, meaning their contents can be changed after creation. You can pass a dictionary to a function
and any changes made to the dictionary will affect the original dictionary.
520 Touchpad Computer Science (Ver. 3.0)-XI

