0% found this document useful (0 votes)
6 views22 pages

Unit 3

The document covers Python's complex data types, including strings, lists, tuples, and dictionaries, along with their manipulation methods. It explains the concept of functions, their advantages, types (built-in and user-defined), and how to define and call them, including details on parameters, return statements, and various argument types. Additionally, it discusses string operations, indexing, slicing, and immutability, along with examples of string functions.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
6 views22 pages

Unit 3

The document covers Python's complex data types, including strings, lists, tuples, and dictionaries, along with their manipulation methods. It explains the concept of functions, their advantages, types (built-in and user-defined), and how to define and call them, including details on parameters, return statements, and various argument types. Additionally, it discusses string operations, indexing, slicing, and immutability, along with examples of string functions.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 22

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

blocks of python programs, string manipulation methods, List manipulation. Dictionary

manipulation, Programming using string, list and dictionary in-built functions. Python

Functions, Organizing python codes using functions.

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.

Advantages of Using Functions

 Breaks the code into smaller chunks:


Functions help in dividing a large program into smaller, manageable parts. Each
function is responsible for a specific task, which makes it easier to understand,
develop, and debug. This modular approach simplifies the overall structure of the
program.

 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.

 Improved readability and maintainability:


Functions make the code more organized and easier to read. When each function has
a meaningful name and a specific purpose, it becomes clear what the code is doing.
This improves the overall readability and makes future updates or maintenance
much simpler.

 Enhances code reusability:


Once a function is written, it can be reused in different parts of the program or even
in other programs. This saves time and effort, especially for commonly used tasks or
calculations.
 Helps in debugging and testing:
Since each function handles a specific part of the task, it's easier to test individual
parts of the code separately. If there's an error, we can isolate and fix it within that
particular function without affecting the rest of the program.

We have to create function once and can be called multiple times in the program.

Types of Functions in Python

In Python, functions are mainly categorized into two types:

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:

 str() – Converts a value to a string.

 type() – Returns the data type of a value or variable.

 max() – Returns the maximum value from a set of values.

 min() – Returns the minimum value.

 pow() – Returns the value of a number raised to a power.

 round() – Rounds a number to the nearest integer or to the specified number of


decimal places.

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.

Creating a user-defined function involves the following steps:

 First, define the function using the def keyword.

 Give the function a meaningful name.

 Specify any required parameters inside parentheses (optional).

 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

To define a function, we use the def keyword followed by:

 The function name.

 A set of parameters in parentheses (if any).

 A colon : to indicate the start of the function body.

 An indented block of code which runs when the function is called.

Syntax:

def function_name(parameter1, parameter2, ..., parameterN):

# 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:

function_name(argument1, argument2, ..., argumentN)

 Formal and actual parameters can have different names.it is not mandatory to
provide same names.

Formal Parameters vs Actual Parameters

 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.

def print_function(college_name): # 'college_name' is a formal parameter

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:

greet("ITS College") # "ITS College" is the actual parameter


Example 1 : example using No parameters passed

def print_function():

print(“Welcome to the ITS”)

print_function()

Example 2 : Example by passing a parameter

def print_function(college_name):

print(“Welcome to the ”,college_name)

clg = input(“Enter College Name”)

print_function(clg)

Example 3: using return statement

def add_numbers(a, b):

return a + b

num1 = 10

num2 = 20

result = add_numbers(num1, num2)

print("The sum is:", result)

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:

def calculate(a, b):

addition = a + b

subtraction = a - b

return addition, subtraction

num1 = 10

num2 = 20

add_result, sub_result = calculate(num1, num2)

print("The sum is:", add_result)

print("The difference is:", sub_result)

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.

Types of Arguments in Python

 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)

fn = input(“Enter First Name”)

ln = input(“Enter Last Name”)

name_print(last_name = ln,first_name = fn)

Default Arguments in Python

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.

def add_numbers(a = 10, b = 30):

return a + b

print(add_numbers())# Output: 30

print(add_numbers(5)) # Output:35

print(add_numbers(3, 4))# Output: 7

Variable length Argument

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

for num in numbers:

total += num

return total

print(add_numbers(1, 2, 3))# Output: 6

print(add_numbers(4, 5, 6, 7, 8)) # Output: 30

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)

print(factorial(5)) # Output: 120

Example 2:

def fibonacci(n):

if n == 0:

return 0
elif n == 1:

return 1

else:

return fibonacci(n - 1) + fibonacci(n - 2)

for i in range(7):

print(fibonacci(i), end=" ") # Output: 0 1 1 2 3 5 8

Lambda Functions / Anonymous Functions

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:

lambda arguments: expression

Example:

add = lambda a, b: a + b

print(add(3, 5)) # Output: 8

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”

In Python, a string is treated as a sequence of bytes, where each byte represents a


character. You can access individual characters in a string using indexing, just like elements in
a list.
Unlike some other languages, Python does not have a separate character data type. A
single character is simply a string of length one.

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)

print(text) # Output: "123"

print(type(text)) # Output: <class 'str'>

str(True) # Output: "True"

str(3.14) # Output: "3.14"

String Operations

Python allows simple and intuitive operations on strings using operators like + and *, which
make it easy to manipulate text.

 + Operator → String Concatenation

The + operator is used to join two or more strings together, creating a new combined string.

str1 = "Hello"

str2 = "World"

result = str1 + " " + str2

print(result) # Output: Hello World

Note: Both operands must be strings. Mixing strings with numbers directly will raise an error.

 Operator → String Repetition


The * operator is used to repeat a string multiple times.

text = "Hi "

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.

Comparision of two Strings(>,<,<=,>=,!=)

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:

print("apple" < "banana") # True, because 'a' comes before 'b'

print("zebra" > "apple") # True, because 'z' comes after 'a'

print("car" <= "carpet") # True, because 'car' is a prefix of 'carpet'

print("dog" >= "dog") # True, because both strings are equal

Note: Python compares strings from left to right, stopping at the first mismatch. If all
characters are equal, the shorter string is considered smaller.

Working with String

In Python, a string is treated as a sequence of characters, where each character is stored


like an element in an array. Every character in the string is assigned a unique index, starting
from 0 for the first character, 1 for the second, and so on.

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]

Note: Indexing starts from 0, not 1.

Example :

text = "ITS College"


print(text[2]) # Output: 'S'

Negative Indexing in Python

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

Neg Index: -11 -10 -9 -8 -7 -6 -5 -4 -3 -2 -1

Why Use It?

It’s a convenient way to access elements from the end without calculating the exact length
of the string.

Example:

text = "ITS College"

print(text[-1]) # Output: 'e' (last character)

print(text[-4]) # Output: 'l' (4th character from end)

Slicing

Slicing in Python allows you to extract a specific portion of a string by specifying a range of
indexes.

Syntax:

string_variable[start : end : step]

 start – the index to begin the slice (inclusive)

 end – the index to stop the slice (exclusive)

 step – the number of steps to skip (default is 1)

Example:

college_name = "ITS College"

print(college_name[1:3]) # Output: 'TS'

Characters from index 1 to 2 are returned (3 is not included).


Omitting Start or End:

If you don’t provide a start or end value, Python uses default values:

 Start defaults to 0

 End defaults to length of the string

Example:

print(college_name[:3]) # Output: 'ITS'

print(college_name[4:]) # Output: 'College'

Negative Indexing in Slicing:

You can also use negative indexing to slice from the end of the string:

print(college_name[-7:-1]) # Output: 'Colleg'

Slicing with Step:

You can define a step to skip characters while slicing.

Example:

print(college_name[0:11:2]) # Output: 'ISColeg'

This takes every second character from index 0 to 10.

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 :

college_name = "ITS Collage"

college_name[-3] = "e" # ❌ This will raise an error

This will result in a TypeError because strings do not support item assignment.

String Functions

1. len() – Returns the number of characters in the string

text = "ITS College"

print(len(text)) # Output: 11

Note : Returns the total number of characters including space.


2. lower() – Converts all characters to lowercase

text = "ITS College"

print(text.lower()) # Output: its college

3. upper() – Converts all characters to uppercase

text = "ITS College"

print(text.upper()) # Output: ITS COLLEGE

4. strip() – Removes leading and trailing whitespaces

text = " ITS College "

print(text.strip()) # Output: 'ITS College'

5. replace(old, new) – Replaces specified text with new text

text = "ITS College"

print(text.replace("College", "Institute")) # Output: ITS Institute

6. find(sub) – Returns index of first occurrence of a substring

text = "ITS College"

print(text.find("C")) # Output: 4

7. split(sep) – Splits the string using a separator

text = "ITS College"

print(text.split(" ")) # Output: ['ITS', 'College']

8. join(iterable) – Joins elements of an iterable with a string separator

words = ['ITS', 'College']

print(" ".join(words)) # Output: ITS College

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:

my_list = [10, "ITS College", 3.14, “ECE”,True]

print(my_list) # Output: [10, "ITS College", 3.14, “ECE”,True]

Accessing Items in a Lists

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:

car_brands = ["Toyota", "BMW", "Honda"]

print(car_brands[0]) # Output: Toyota

print(car_brands[2]) # Output: Honda

Note: Trying to access an index that doesn’t exist will result in an IndexError.

Example:

print(car_brands[5]) # ❌ IndexError: list index out of range

Negative Indexing:

You can also use negative indexes to access elements from the end of the list.

print(car_brands[-1]) # Output: Honda

Modifying items in 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 = ["Toyota", "BMW", "Honda"]

car_brands[1] = "Mercedes"

print(car_brands) # Output: ['Toyota', 'Mercedes', 'Honda']

Assigning a List to Another List

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:

mobiles1 = ["Samsung", "iPhone", "OnePlus"]

mobiles2 = mobiles1

mobiles2[0] = "Realme"

print(mobiles1) # Output: ['Realme', 'iPhone', 'OnePlus']

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:

list_variable[start : end : step]

 start: Index to begin the slice (inclusive)

 end: Index to stop the slice (exclusive)

 step: Optional; defines the interval between elements

Example:

mobiles = ["Samsung", "iPhone", "OnePlus", "Realme", "Vivo"]

print(mobiles[1:4]) # Output: ['iPhone', 'OnePlus', 'Realme']

This returns elements from index 1 to 3. Index 4 is not included.


Omitting Start/End:

You can skip start or end values to default from the beginning or till the end

Example:

print(mobiles[:3]) # Output: ['Samsung', 'iPhone', 'OnePlus']

print(mobiles[2:]) # Output: ['OnePlus', 'Realme', 'Vivo']

Using Step:

The step value can be used to skip elements.

Example:

print(mobiles[0:5:2]) # Output: ['Samsung', 'OnePlus', 'Vivo']

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:

phones = ["iPhone", "Samsung"]

brands = ["OnePlus", "Realme"]

all_phones = phones + brands

print(all_phones) # Output: ['iPhone', 'Samsung', 'OnePlus', 'Realme']

Note: It doesn’t modify the original lists; it returns a new list.

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)

# Output: ['Nokia', 'Nokia', 'Nokia']

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:

phones = ["iPhone", "Samsung", "Realme"]

print("iPhone" in phones) # True

print("OnePlus" not in phones) # True

Returns a Boolean (True or False) based on presence or absence of the item.

Iteration (Using for Loop)

You can loop through each item in a list using a for loop, allowing you to process or display
each element individually.

for phone in phones:

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()

 Adds an item at the end of the list.

cars = ["Toyota", "BMW"]

cars.append("Audi")

print(cars) # ['Toyota', 'BMW', 'Audi']

insert(index, element)

 Inserts an element at a specific position.


cars.insert(1, "Tesla")

print(cars) # ['Toyota', 'Tesla', 'BMW', 'Audi']

remove(element)

 Removes the first occurrence of the specified element.

cars.remove("BMW")

print(cars) # ['Toyota', 'Tesla', 'Audi']

pop([index])

 Removes and returns an element from the list. By default, removes the last item.

last_car = cars.pop()

print(last_car) # Audi

print(cars) # ['Toyota', 'Tesla']

sort()

 Sorts the list in ascending order (modifies original list).

prices = [30000, 15000, 45000]

prices.sort()

print(prices) # [15000, 30000, 45000]

reverse()

 Reverses the order of the list.

cars = ["Toyota", "BMW", "Audi"]

cars.reverse()

print(cars) # ['Audi', 'BMW', 'Toyota']

count(element)

 Returns the number of times an element appears in the list.

colors = ["red", "blue", "red", "green"]

print(colors.count("red")) # 2

index(element)

 Returns the index of the first occurrence of the 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.

Why Use It?

 Reduces multiple lines of loops and append() calls into a single line.

 Makes the code cleaner and more Pythonic.

Syntax:

[expression for item in iterable if condition]

 expression: operation to perform (e.g., x * x)

 item: variable that takes the value from the iterable

 iterable: source data (e.g., list, range)

 condition: optional filter (e.g., if x % 2 == 0)

Example 1: Get squares of numbers from 1 to 5

squares = [x * x for x in range(1, 6)]

print(squares) # [1, 4, 9, 16, 25]

Example 2: Get even numbers from 0 to 9

even_numbers = [x for x in range(10) if x % 2 == 0]

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.

Why Use It?

 Makes code cleaner and avoids repetitive indexing (like x[0], x[1])

 Useful for returning multiple values from functions

Example:

car = ["Tesla", "Model 3", 2023]

brand, model, year = car


print(brand) # Tesla

print(year) # 2023

With the * operator:

If you're not sure how many values will be there, you can use * to capture multiple values
into a list.

first, *middle, last = [1, 2, 3, 4, 5]

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.

Why Use Mutable Sequences?

 You can update elements

 Add or remove items

 Reuse and modify without creating a new object

Example:

phones = ["iPhone", "Samsung", "Realme"]

phones[1] = "Pixel"

print(phones) # ['iPhone', 'Pixel', 'Realme']

You can also do:

phones.append("OnePlus")

phones.remove("iPhone")

phones.sort()

Contrast with Immutable Sequences:

 Strings and tuples are immutable: once created, they cannot be changed.

 Lists are mutable: you can change the values, order, or size.

Abstract Data Type


Abstract Data Types are the data structures that are not built-in but are crucial for solving
specific types of problems in programming. These structures help in organizing and
managing data efficiently when predefined types like lists, tuples, or dictionaries aren’t
enough.

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

Think of a stack of books.

 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

A stack supports the following basic operations:

push(item)

 Adds an item to the top of the stack.

pop()

 Removes and returns the top item from the stack.

peek() or top()

 Returns the top item without removing it (not built-in, but you can do this using
indexing).

isEmpty()

 Checks whether the stack is empty.

size()
 Returns the number of elements in the stack.

When to Use a Stack?

 Undo/Redo functionality in editors

 Backtracking (e.g., in puzzles or recursion)

 Expression evaluation (postfix/prefix)

 Function call stack in programming languages

Tuple definition

Difference berween tuple and list

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy