Unit 3
Unit 3
Python Complex data types: Using string data type and string operations, Defining list
and list slicing, Use of Tuple data type. String, List and Dictionary, Manipulations Building
manipulation, Programming using string, list and dictionary in-built functions. Python
Functions
A function is a named block of code that performs a specific task. It allows us to group a set
of statements together so that they can be reused whenever needed in a program. Instead
of writing the same code multiple times, we can simply call the function wherever required.
For example, functions like add(a, b), print(), and type() help us perform addition, display
output, or check the type of a variable, respectively.
Redundancy is avoided:
When a particular task needs to be performed multiple times in a program, instead
of writing the same code repeatedly, we can simply call the function. This eliminates
repetition and reduces the chances of errors, making the code more efficient and
concise.
We have to create function once and can be called multiple times in the program.
1. Built-in Functions
These are the functions that are already provided by Python. You can directly use them
without needing to define them yourself. These functions are a part of the Python Standard
Library and help in performing common tasks quickly.
Examples:
2. User-Defined Functions
These are the functions that you, as a programmer, create yourself to perform a specific
task. When a piece of logic or a block of code needs to be used multiple times, you can
define it inside a function and call it whenever required.
Write the block of code (statements) that you want the function to execute.
Later, invoke or call the function wherever you need it in your program.
User-defined functions can also accept parameters, which are values passed into the
function when it is called, and they can return a result after processing.
Defining a Function in Python
Syntax:
# set of statements
Calling a Function
After defining a function, we need to call it to execute the code inside it. This is done by
writing the function name followed by parentheses, passing any required arguments inside.
Syntax:
Formal and actual parameters can have different names.it is not mandatory to
provide same names.
Formal Parameters:
These are the variable names listed in the function definition. They act as
placeholders for the values the function will receive when it is called.
print(college_name)
Actual Parameters:
These are the real values or arguments passed to the function during the function call. They
are assigned to the corresponding formal parameters.
Example:
def print_function():
print_function()
def print_function(college_name):
print_function(clg)
return a + b
num1 = 10
num2 = 20
return Statement
The return statement is used inside a function to send a result or output back to the place
where the function was called. It allows the function to produce a value that can be stored in
a variable, used in an expression, or printed.
Once the return statement is executed, the function terminates immediately, and the
specified value(s) are returned to the caller.
Python also allows you to return multiple values by separating them with commas. These
values are returned as a tuple.
Example:
addition = a + b
subtraction = a - b
num1 = 10
num2 = 20
Keyword Arguemnts
Keyword arguments (often called keyword args) allow you to pass arguments to a function
by explicitly specifying the name of the parameter along with its value. This makes the
function call more readable and helps avoid confusion about the order of the arguments.
For example, instead of just passing values based on position, you can clearly indicate which
value corresponds to which parameter.
Positional Arguments:
These are arguments passed to a function in the exact order of the parameters
defined. The position matters here, so the first argument is assigned to the first
parameter, the second to the second, and so on.
Keyword Arguments:
These arguments are passed by explicitly naming the parameters during the function
call. The order of keyword arguments does not matter because each argument is
matched by its parameter name.
Using keyword arguments improves code clarity and reduces errors, especially in functions
with many parameters.
Example:
def name_print(first_name,last_name)
print(first_name,last_name)
Sometimes, when calling a function, you may choose not to provide a value for every
parameter. In such cases, Python allows you to assign default values to parameters when
defining the function. These are called default arguments.
If the caller does not provide a value for a parameter with a default, the function
automatically uses the default value specified. This makes the function more flexible and
allows it to be called with fewer arguments when appropriate.
return a + b
print(add_numbers())# Output: 30
print(add_numbers(5)) # Output:35
Sometimes, you may want to create a function that can accept any number of arguments,
instead of a fixed number. This is where variable-length arguments come in handy.
In Python, you can define a function to accept a variable number of arguments by using an
asterisk (*) before a parameter name. This parameter collects all the extra positional
arguments passed to the function into a tuple. This allows the function to handle flexible
input sizes without knowing in advance how many arguments it will receive.
Example:
def add_numbers(*numbers):
total = 0
total += num
return total
print(add_numbers())
Recursive Functions
A recursive function is a function that calls itself to solve smaller parts of the same problem
until it reaches a final answer. It’s like solving a puzzle step-by-step by reducing the problem
into smaller versions of itself.
A base condition is a point where the function stops calling itself. Without it, the function
would call itself forever and crash the program.
Example 1:
def factorial(n):
if n == 0 or n == 1:
return 1
else:
return n * factorial(n - 1)
Example 2:
def fibonacci(n):
if n == 0:
return 0
elif n == 1:
return 1
else:
for i in range(7):
Lambda functions are small, anonymous functions in Python that don’t require a name like
regular functions defined with def. They are also known as inline functions and are mainly
used for short, simple operations that can be written in a single line.
Lambda functions use the lambda keyword, followed by the parameters, a colon :, and the
expression to evaluate. They can take any number of arguments but must contain only one
expression, which is automatically returned.
Syntax:
Example:
add = lambda a, b: a + b
String
A string in Python is a sequence of characters that may include letters, digits, symbols,
punctuation, and spaces. Strings are always enclosed within single (' ') or double (" ")
quotes.
str1 = “text”
str2 = “124”
str3 = “1ab4”
single_character_string = “A”
empty_string = “”
str() Function
The str() function is used to type cast (or convert) a value from another data type—such as
a number, boolean, or even a list—into a string format.
This is especially useful when you want to concatenate values with strings, display data, or
store values in text format.
Example :
num = 123
text = str(num)
String Operations
Python allows simple and intuitive operations on strings using operators like + and *, which
make it easy to manipulate text.
The + operator is used to join two or more strings together, creating a new combined string.
str1 = "Hello"
str2 = "World"
Note: Both operands must be strings. Mixing strings with numbers directly will raise an error.
result = text * 3
print(result) # Output: Hi Hi Hi
Note: The second operand must be an integer. You can’t multiply a string by a float or
another string.
In Python, you can compare two strings using relational operators such as >, <, <=, >=, ==,
and !=. These comparisons are done lexicographically, meaning character by character based
on their Unicode values (similar to dictionary order).
Example:
Note: Python compares strings from left to right, stopping at the first mismatch. If all
characters are equal, the shorter string is considered smaller.
String: I T S C o l l e g e
Pos Index: 1 2 3 4 5 6 7 8 9 10 11
This indexing allows us to easily access individual characters using square brackets [] along
with the index number.
Syntax:
string_name[index]
Example :
In Python, negative indexing allows you to access elements of a string (or any sequence like
a list or tuple) from the end rather than the beginning.
Instead of starting at 0 (the first character), negative indices start at -1 (the last character), -2
(second last), and so on.
String: I T S C o l l e g e
It’s a convenient way to access elements from the end without calculating the exact length
of the string.
Example:
Slicing
Slicing in Python allows you to extract a specific portion of a string by specifying a range of
indexes.
Syntax:
Example:
If you don’t provide a start or end value, Python uses default values:
Start defaults to 0
Example:
You can also use negative indexing to slice from the end of the string:
Example:
Immutability
In Python, strings are immutable, which means once a string is created, you cannot change
or modify its individual characters. Any operation that seems to modify a string will actually
create a new string instead of changing the original one.
Example :
This will result in a TypeError because strings do not support item assignment.
String Functions
print(len(text)) # Output: 11
print(text.find("C")) # Output: 4
Lists
Lists
A list in Python is a collection of ordered, changeable (mutable), and indexed elements. It is
one of the most commonly used data structures in Python to store multiple items in a single
variable.
Lists can hold elements of different data types such as integers, strings, floats, or even other
lists. They are defined using square brackets [], and items are separated by commas.
Syntax:
List_name = [item1,item2,…..,item n]
Example:
In Python, you can access individual items in a list using indexing. Each item in the list is
assigned a position, starting from index 0 for the first element, 1 for the second, and so on.
You use square brackets [] along with the index to access a specific item.
Example:
Note: Trying to access an index that doesn’t exist will result in an IndexError.
Example:
Negative Indexing:
You can also use negative indexes to access elements from the end of the list.
In Python, lists are mutable, meaning you can change the value of individual elements after
the list has been created. This makes lists very flexible for use in dynamic programs.
To modify an item, simply access it by its index and assign a new value using the assignment
operator =.
Example:
car_brands[1] = "Mercedes"
In Python, when you assign one list to another using the = operator, it does not create a new
copy of the list. Instead, both variables point to the same memory location, meaning
changes made through one variable will affect the other as well.
Example:
mobiles2 = mobiles1
mobiles2[0] = "Realme"
Slicing in Lists
Slicing in Python allows you to extract a specific portion of a list by specifying a range of
indexes. This helps when you want to work with only a part of the list instead of the entire
list.
syntax:
Example:
You can skip start or end values to default from the beginning or till the end
Example:
Using Step:
Example:
List Operations
Concatenation (+ Operator)
Concatenation means joining two or more lists together using the + operator. It creates a
new list by combining the elements of the original lists in the same order.
Example:
Repetition (* Operator)
The * operator allows you to repeat a list multiple times. This is useful when you want to
duplicate the same set of items.
Example:
repeat_list = ["Nokia"] * 3
print(repeat_list)
The original list remains unchanged, and a new list is created with repeated items.
Membership (in, not in)
Membership operators are used to check if an item exists or does not exist in the list.
Example:
You can loop through each item in a list using a for loop, allowing you to process or display
each element individually.
print(phone)
This is a very common and powerful way to access list elements one by one.
list() function
The list() function is a built-in function used to create a list in Python. It can convert iterable
objects like strings, tuples, sets, or dictionaries into a list.
Example 1:
name = "ITS"
char_list = list(name)
print(char_list)
List Functions
append()
cars.append("Audi")
insert(index, element)
remove(element)
cars.remove("BMW")
pop([index])
Removes and returns an element from the list. By default, removes the last item.
last_car = cars.pop()
print(last_car) # Audi
sort()
prices.sort()
reverse()
cars.reverse()
count(element)
print(colors.count("red")) # 2
index(element)
print(colors.index("green")) # 3
List Comprehension
List comprehension provides a concise and readable way to create new lists from iterables
like ranges, strings, or other lists.
Reduces multiple lines of loops and append() calls into a single line.
Syntax:
print(even_numbers) # [0, 2, 4, 6, 8]
Sequence Unpacking
Sequence unpacking means assigning individual values from a sequence (like a list or tuple)
directly into variables in a single line.
Makes code cleaner and avoids repetitive indexing (like x[0], x[1])
Example:
print(year) # 2023
If you're not sure how many values will be there, you can use * to capture multiple values
into a list.
print(first) # 1
print(middle) # [2, 3, 4]
print(last) # 5
Mutable Sequences
A mutable sequence means the content of the sequence can be changed after it is created.
In Python, lists are the most commonly used mutable sequences.
Example:
phones[1] = "Pixel"
phones.append("OnePlus")
phones.remove("iPhone")
phones.sort()
Strings and tuples are immutable: once created, they cannot be changed.
Lists are mutable: you can change the values, order, or size.
ADTs include important structures like Stack, Queue, Graph, Linked List, and many others.
They provide a logical description of how the data is organized and what operations can be
performed — but not how they are implemented behind the scenes.
In simple terms, ADTs can be thought of as custom classes that hold a group of values along
with a set of operations (functions or methods) that can be performed on those values.
These operations define how the data behaves — such as insertion, deletion, searching, and
traversing.
Stack
A Stack is a linear data structure that follows the LIFO (Last In, First Out) principle.
This means that the last element added to the stack will be the first one to be removed —
just like a stack of plates.
Real-life Analogy
When you place a new book on top, it becomes the last item added.
When you remove a book, you take off the top one first — you can’t take the middle
one directly without removing the ones above it.
Stack Operations
push(item)
pop()
peek() or top()
Returns the top item without removing it (not built-in, but you can do this using
indexing).
isEmpty()
size()
Returns the number of elements in the stack.
Tuple definition