UNIT-3
Unit Title: Complex Data Types & Functions in Python
Objective:
To understand and work with Python's complex data types like Strings, Lists, Tuples, and
Dictionaries. Learn how to manipulate them and organize reusable code using functions.
STRING DATA TYPE & STRING
OPERATIONS
What is a String?
A string is a sequence of characters and can contain letters, numbers, symbols and even spaces.
It must be enclosed in quotes (‘ ' or ” ") and String is Immutable Data Type.
(or)
A string is a sequence of characters enclosed in single, double, or triple quotes.
String Declaration:
str1 = 'Hello’
str2 = "Python Programming”
str3 = '''This is a multi-line string'''
STRING LENGTH
# Example
text = "Python"
print(len(text)) # Output: 6
String Indexing & Slicing
#Example
text = "Python"
print(text[0]) # 'P'
print(text[-1]) # 'n'
Slicing:
# Example
text = "Python"
print(text[0:3]) # 'Pyt'
print(text[2:]) # 'thon'
print(text[:4]) # 'Pyth'
print(text[-3:]) # 'hon’
String Concatenation and Repetition:
# Example
str1 = "Hello"
str2 = "World"
print(str1 + " " + str2) # 'Hello World'
print(str1 * 3) # 'HelloHelloHello'
String Membership:
# Example
print('Py' in 'Python') # True
print('Java' not in 'Python') # True
String Comparison:
# Example
print("apple" == "Apple") # False
print("abc" < "abd") # True (lexicographically)
Case Conversion:
# Example
text = "Hello World"
print(text.lower()) # hello world
print(text.upper()) # HELLO WORLD
print(text.title()) # Hello World
print(text.capitalize())# Hello world
print(text.swapcase()) # hELLO wORLD
Search Methods:
# Example
text = "Hello Python"
print(text.find("Python")) #6
print(text.index("Hello")) #0
print(text.count("o")) #2
Strip and Replace:
# Example
data = " Hello "
print(data.strip()) # 'Hello'
print(data.lstrip()) # 'Hello '
print(data.rstrip()) # ' Hello'
print(data.replace("l", "*")) # ' He**o '
Startswith & Endswith:
#Example
filename = "data.csv"
print(filename.startswith("data")) # True
print(filename.endswith(".csv")) # True
Splitting and Joining:
sentence = "Python is fun"
words = sentence.split() # ['Python', 'is', 'fun']
print(words)
joined = "-".join(words) # 'Python-is-fun'
print(joined)
Escape Characters:
# Example
print("Hello\nWorld") # newline
print("She said \"Hi\"") # double quote
print('It\'s Python') # single quote
String Immutability:
# Example
text = "Python"
# text[0] = 'J' ❌ This will give error
text = "Java" # ✅ You can reassign, but not modify in place
STRING IMMUTABILITY
text = "Python"
# text[0] = 'J' ❌ This will give error
text = "Java" # ✅ You can reassign, but not modify in place
LISTS AND LIST SLICING
Lists are ordered, mutable collections.
Can store heterogeneous data types.
Allow Duplicates:-
Since lists are indexed, lists can have items with the same value:
#EX
list1 = ["apple", "banana", "cherry", "apple", "cherry"]
print(list1)
TABLE OF LIST METHODS
Method Description Example
append() Add element at end fruits.append("mango")
insert() Add at specific index fruits.insert(1, "orange")
remove() Remove by value fruits.remove("banana")
pop() Remove last / by index fruits.pop() or fruits.pop(1)
sort() Sort the list fruits.sort()
reverse() Reverse list fruits.reverse()
len() Get list length len(fruits)
index() Get index of a value fruits.index("apple")
PYTHON LIST METHODS – DETAILED
EXPLANATION WITH EXAMPLES
append(): Add an element at the end of the list
# code
fruits = ["apple", "banana"]
fruits.append("mango")
print(fruits)
insert(index, value): Add an element at a specific index
#code
fruits = ["apple", "banana"]
fruits.insert(1, "orange")
print(fruits)
remove(value): Removes the first occurrence of a value
#code
fruits = ["apple", "banana", "cherry"]
fruits.remove("banana")
print(fruits)
pop(): Removes and returns the last element
# code
fruits = ["apple", "banana", "cherry"]
last_item = fruits.pop()
print("After pop:", fruits)
print("Removed item:", last_item)
pop(index): Removes and returns element at a specific index
# code
fruits = ["apple", "banana", "cherry"]
removed = fruits.pop(1)
print("After pop(1):", fruits)
print("Removed:", removed)
sort(): Sorts the list in ascending order
#code
numbers = [5, 3, 8, 1]
numbers.sort()
print(numbers)
reverse(): Reverses the order of the list
#code
fruits = ["apple", "banana", "cherry"]
fruits.reverse()
print(fruits)
len(): Returns the number of items in the list
#code
fruits = ["apple", "banana", "cherry"]
print("List length:", len(fruits))
Output:
List length: 3
index(value): Returns the index of the first matching value
#code
fruits = ["apple", "banana", "cherry", "banana"]
print("Index of 'banana':", fruits.index("banana"))
Output: Index of 'banana': 1
WHAT IS A TUPLE
A tuple is an ordered, immutable (unchangeable) collection of
items. Tuples are written using parentheses (), and they can hold
multiple data types.
#code
my_tuple = ("apple", "banana", "cherry")
print(my_tuple)
Tuple Characteristics:-
Ordered – elements maintain insertion order.
Immutable – you cannot change, add, or remove elements after
creation.
Allows duplicates – same value can appear multiple times.
Creating Tuples:-
#code
fruits = ("apple", "banana", "cherry")
print(fruits)
Output:
('apple', 'banana', 'cherry')
Tuple with mixed data types:-
# code
person = ("John", 25, True)
print(person)
Output:
('John', 25, True)
TUPLE METHODS
count(): Returns number of times a value appears
#code
colors = ("red", "blue", "red", "green", "red")
count_red = colors.count("red")
print("Count of 'red':", count_red)
index(): Returns the index of the first occurrence of a value
#code
colors = ("red", "green", "blue", "green", "yellow")
index_green = colors.index("green")
print("Index of 'green':", index_green)
Accessing Tuple Elements:-
#code
fruits = ("apple", "banana", "cherry")
print(fruits[1]) # Output: banana
Tuple Slicing:-
#code
fruits = ("apple", "banana", "cherry", "mango")
print(fruits[1:3]) # Slices from index 1 to 2
TUPLE VS LIST
Feature Tuple List
Syntax () []
Mutable ❌ No ✅ Yes
Performance ✅ Faster Slower
Methods Limited (count, index) Many (append, pop, etc.)
DICTIONARY
What is a Dictionary:- A dictionary in Python is an unordered
collection of data in a key:value pair format.
It is mutable, indexed by keys, and allows fast lookup.
student = {
"name": "Alice",
"age": 20,
"city": "Delhi"
}
print(student["name"]) # Output: Alice
print(student.get("city")) # Output: Delhi
TABLE OF DICTIONARY METHODS
Method Description Example
keys() Returns all keys student.keys()
values() Returns all values student.values()
items() Returns key-value pairs student.items()
get() Gets value for a key student.get("age")
update() Adds/updates key-value pairs student.update({"age": 21})
pop() Removes key and its value student.pop("city")
clear() Clears entire dictionary student.clear()
keys() – Returns all keys in the dictionary
#code
student = {"name": "Alice", "age": 20, "city": "Delhi"}
print(student.keys())
values() – Returns all values
#code
print(student.values())
items() – Returns list of (key, value) pairs
#code
print(student.items())
get(key) – Retrieves value for a key
#code
print(student.get("age")) # 20
print(student.get("gender")) # None (does not crash like student["gender"])
update() – Updates dictionary with new key-value pairs
#code
student.update({"age": 21, "gender": "female"})
print(student)
pop(key) – Removes item with the specified key
#code
student.pop("city")
print(student)
clear() – Removes all key-value pairs
#code
student.clear()
print(student)
TOPIC: PYTHON FUNCTIONS &
ORGANIZING CODE USING FUNCTIONS
Introduction to Functions:- A function is a block of code which only runs when it
is called.
You can pass data, known as parameters, into a function.
A function can return data as a result.
Why Use Functions?
• Improves code readability and organization
• Promotes reusability (write once, use many times)
• Helps in modular programming
• Makes testing and debugging easier
Types of Functions in Python:-
Type Description
Built-in Functions Predefined (e.g., len(), sum())
Created by users using def
User-defined Functions
Lambda Functions Anonymous, single-expression functions
Creating a Function:-In Python a function is defined using the def keyword
# Code
def my_function():
print("Hello from a function")
Calling a Function:-To call a function, use the function name followed by
parenthesis
#Code
def my_function():
print("Hello from a function")
my_function()
#code
def my_function(fname):
print(fname + " Refsnes")
my_function("Emil")
Parameter:-
A parameter is a variable defined inside the parentheses in the function definition.
It acts as a placeholder for the value you pass when you call the function.
In your code:
fname is the parameter.
Argument:-
An argument is the actual value passed to the function when it is called.
Arguments are assigned to parameters when the function is executed.
In your code:
"Emil"
# code
def my_function(fname, lname):
print(fname + " " + lname)
my_function("Emil", "Refsnes")
Arbitrary Arguments, *args:- If you do not know how many arguments that will
be passed into your function, add a * before the parameter name in the
function definition.
This way the function will receive a tuple of arguments, and can access the
items accordingly:
If the number of arguments is unknown, add a * before the parameter name:
def my_function(*kids):
print("The youngest child is " + kids[2])
my_function("Emil", "Tobias", "Linus")
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")
Default Parameter Value:- If we call the function without argument, it uses the
default value.
#code
def my_function(country = "Norway"):
print("I am from " + country)
my_function("Sweden")
my_function("India")
my_function()
my_function("Brazil")
Passing a List as an Argument:- You can send any data types of argument to a
function (string, number, list, dictionary etc.), and it will be treated as the
same data type inside the function.
E.g. if you send a List as an argument, it will still be a List when it reaches
the function:
#code
def my_function(food):
for x in food:
print(x)
fruits = ["apple", "banana", "cherry"]
my_function(fruits)
Return Values:- To let a function return a value, use the return statement.
#code
def my_function(x):
return 5 * x
print(my_function(3))
print(my_function(5))
print(my_function(9))