Python Complex Data Types and
Functions - Lecture Notes
1. String Data Type and String Operations
Strings in Python are sequences of characters, enclosed either in single, double, or triple
quotes.
Common string operations include concatenation, repetition, indexing, and slicing.
Example:
text = "Hello, World!"
print(text[0]) # Output: H
print(text[0:5]) # Output: Hello
print(text.lower()) # Output: hello, world!
2. Defining List and List Slicing
Lists are ordered, mutable collections of items. They are defined using square brackets [].
Slicing allows retrieval of a portion of the list.
Example:
numbers = [1, 2, 3, 4, 5]
print(numbers[1:4]) # Output: [2, 3, 4]
numbers.append(6)
print(numbers) # Output: [1, 2, 3, 4, 5, 6]
Python uses zero-based indexing.
fruits = ["apple", "banana", "cherry"]
print(fruits[0]) # Output: apple
print(fruits[2]) # Output: cherry
Negative indexing starts from the end:
print(fruits[-1]) # Output: cherry
List Slicing
Slicing is used to extract a portion (sublist) of a list. The syntax is
list[start:stop:step]
• start: index where the slice starts (inclusive)
• stop: index where the slice ends (exclusive)
• step: interval between elements (default is 1)
numbers = [10, 20, 30, 40, 50, 60, 70]
print(numbers[1:5]) # [20, 30, 40, 50]
print(numbers[:4]) # [10, 20, 30, 40]
print(numbers[3:]) # [40, 50, 60, 70]
print(numbers[::2]) # [10, 30, 50, 70]
print(numbers[::-1]) # [70, 60, 50, 40, 30, 20, 10]
# Reverse a list
reversed_list = numbers[::-1]
# Extract every 3rd element from the list
step_slice = numbers[::3]
# Slice from index 2 to the second-last element
mid_slice = numbers[2:-1]
3. Use of Tuple Data Type
Tuples are similar to lists but are immutable. They are defined using parentheses ().
Example:
coordinates = (10, 20)
print(coordinates[0]) # Output: 10
# A simple tuple
coordinates = (10, 20)
# A tuple with mixed data types
person = ("Alice", 25, "Engineer")
# A tuple without parentheses (tuple packing)
data = 1, 2, 3
# An empty tuple
empty = ()
# A tuple with one element (must include a comma)
single_element = (42,)
Tuple Slicing
Tuples can be sliced just like lists:
t = (1, 2, 3, 4, 5)
print(t[1:4]) # Output: (2, 3, 4)
print(t[:3]) # Output: (1, 2, 3)
print(t[::-1]) # Output: (5, 4, 3, 2, 1)
Iterating Through a Tuple
colors = ("red", "green", "blue")
for color in colors:
print(color)
Feature List Tuple
Syntax [] ()
Feature List Tuple
Mutable Yes No
Indexed Yes Yes
Slicing Yes Yes
Use Case Dynamic data Static data
4. Dictionary Manipulation
Dictionaries are unordered collections of key-value pairs. They are defined using curly
braces {}.
Example:
student = {"name": "Alice", "age": 23}
print(student["name"]) # Output: Alice
student["age"] = 24
print(student) # Output: {'name': 'Alice', 'age': 24}
5. Manipulation Methods
String Methods: upper(), lower(), find(), replace(), split()
List Methods: append(), remove(), pop(), sort(), reverse()
Dictionary Methods: keys(), values(), items(), get(), update()
6. Programming Examples
Example 1: String Functions
text = "Python Programming"
print(text.replace("Python", "Java")) # Output: Java Programming
Example 2: List Functions
fruits = ['apple', 'banana', 'cherry']
fruits.remove('banana')
print(fruits) # Output: ['apple', 'cherry']
Example 3: Dictionary Functions
grades = {'Math': 90, 'Science': 85}
print(grades.get('Math')) # Output: 90
grades.update({'English': 88})
print(grades) # Output: {'Math': 90, 'Science': 85, 'English': 88}
7. Python Functions and Organizing Code
Functions are blocks of reusable code. They are defined using the def keyword.
Example:
def greet(name):
return "Hello " + name
print(greet("Alice")) # Output: Hello Alice
Functions help modularize and organize code logically.
1. Basic Function Programs
Example 1: Add two numbers using a function
def add(a, b):
return a + b
print("Sum:", add(10, 20)) # Output: Sum: 30
Example 2: Check even or odd using a function
def is_even(num):
return num % 2 == 0
print("Is 4 even?", is_even(4)) # Output: True
Example 3: Find maximum of three numbers
def find_max(x, y, z):
return max(x, y, z)
print("Maximum:", find_max(10, 20, 5)) # Output: 20
2. Recursive Function Programs
Example 1: Factorial using recursion
def factorial(n):
if n == 0:
return 1
else:
return n * factorial(n - 1)
print("Factorial of 5:", factorial(5)) # Output: 120
Example 2: Fibonacci series using recursion
def fibonacci(n):
if n <= 1:
return n
else:
return fibonacci(n-1) + fibonacci(n-2)
for i in range(6):
print(fibonacci(i), end=" ") # Output: 0 1 1 2 3 5
Example 3: Sum of digits using recursion
def sum_of_digits(n):
if n == 0:
return 0
else:
return n % 10 + sum_of_digits(n // 10)
print("Sum of digits of 1234:", sum_of_digits(1234)) # Output: 10
Example 4: Power function using recursion
def power(base, exponent):
if exponent == 0:
return 1
else:
return base * power(base, exponent - 1)
print("2^5 =", power(2, 5)) # Output: 32