Top Banner Ad

BCC302 — Unit 3: Python Complex data types

Table of Contents (24 sections)

BCC302 · Python Programming · Unit 3

Python Complex data types

Unit Scope & Exam Weightage: This is the most program-heavy unit: string operations and slicing, list definition, slicing and comprehension, tuples and unpacking, dictionary CRUD and built-ins, and functions/lambda for organising code. The supplied question set has 39 recorded clusters, including output-prediction questions and many 7-mark programming tasks (character frequency, dictionary merge, prime/perfect-square helpers, removenth, filters).


Front Page: Importance-Wise Topic Roadmap (2023–26 PYQs)

Priority Topic (Exact Syllabus) PYQs Asked Marks Weightage Tag
1 Using string data type and string operations; String; string manipulation methods; Programming using string 13 (2023-24 ×7, 2024-25 ×2, 2025-26 ×4) 2m ×4 + 7m ×9 Survival Mode
2 Defining list and list slicing; List manipulation; List comprehension 8 (2023-24 ×4, 2024-25, 2025-26 ×3) 2m ×3 + 7m ×5 Slicing Drills
3 Python Functions; Organizing python codes using functions 8 (2023-24 ×4, 2024-25, 2025-26 ×3) 2m ×2 + 7m ×6 Program Bank
4 Dictionary manipulation; List and Dictionary 7 (2023-24 ×3, 2024-25 ×3, 2025-26) 2m + 7m ×6 CRUD
5 Use of Tuple data type 5 (2024-25 ×2, 2025-26 ×3) 2m + 7m ×4 Comparison
6 Manipulations Building blocks of python programs Integrated in #1–#5 — Supporting

2-Hour Last-Night Survival Checklist:

  1. Slicing formula (Priority 1–2): seq[start:stop:step] — start inclusive, stop exclusive; negative indices count from the end; [::-1] reverses.
  2. String methods: lower, upper, strip, split, join, replace, find, count, startswith — write one line of output for each.
  3. List vs tuple vs dict: list mutable [], tuple immutable (), dict key→value {}; remember dict.update() for merging.
  4. Functions: def name(params): + return; have five ready — sum list, char frequency, perfect square, removenth, smallest nested list.
  5. Output prediction: trace list comprehension [i**2 for i in x if i%2==0] → [4,16] and filter(bool, l) → truthy values only.

1. Complex Data Types: Overview

Complex (composite) data type: A type that can hold several values together under one name. Python's principal containers are string (text sequence), list, tuple, dictionary and set. Strings, lists and tuples are ordered sequences; dictionaries map keys to values; sets hold unique values.

Type Literal Ordered Mutable Allows duplicates Example
str "Python" Yes No Yes s[0] → 'P'
list [1, 2] Yes Yes Yes L.append(3)
tuple (1, 2) Yes No Yes t[1] → 2
dict {"a":1} Keys (insertion order) Yes No keys, yes values d["a"] → 1
set {1, 2} No Yes No {1,1} → {1}

After-Topic PYQ:

  • 2025-26 (Sec C, 7 Marks): "What are complex data types in Python? Explain strings, lists, tuples, and dictionaries with examples."

2. Strings: Slicing and Operations

String: An immutable sequence of Unicode characters. Indexing starts at 0; negative indices start at −1 from the end. Because strings are immutable, every "change" creates a new string.

2.1 Indexing and Slicing

General slice: s[start:stop:step] — start included, stop excluded, step default 1. Omitted start means 0; omitted stop means end; s[::-1] reverses.

s = "PythonProgram"
print(s[0], s[-1])       # P m
print(s[0:6])            # Python
print(s[6:])             # Program
print(s[::2])            # PtoRm (indices 0,2,4,6,8,10)
print(s[::-1])           # margorPnohtyP

2.2 Common String Operators and Methods

Operation Example Result
Concatenation + "BCA" + "302" "BCA302"
Repetition * "*" * 3 "***"
Membership in "Python" in "Python is fun" True
len() len("Python") 6
lower()/upper() "Py".lower() "py"
strip() " hi \n".strip() "hi"
split() "a,b,c".split(",") ['a','b','c']
join() "&".join("Hi") "H&i"
replace() "Hello".replace("l","L") "HeLLo"
find()/count() "banana".find("a"), .count("a") 1, 3
startswith() "Python".startswith("Py") True
def vowels(s):
    return "".join(c for c in s.lower() if c in "aeiou")
print(vowels("Education"))   # euaio (check by tracing lowercased text)

After-Topic PYQs:

  • 2024-25, 2025-26 (Sec C, 7 Marks): "Explain string slicing and string operations in Python."
  • 2025-26 (Sec C, 7 Marks): "Discuss string operations and built-in functions. Write a program to count vowels in a string."
  • 2025-26 (Sec C, 7 Marks): "Describe string manipulation methods. Write a program to replace characters in a string."
  • 2024-25 (Sec C, 7 Marks): "Explain commonly used string methods in Python. Write a program using the following operations on the given string: text = "Machine Learning". Use the following methods: lower(), upper(), strip(), replace(), find(), count()"
  • 2023-24 (Sec A, 2 Marks): "Describe the purpose of the split() method in string manipulation."

3. Lists, Slicing and Comprehension

List: An ordered, mutable sequence written in square brackets. It can store mixed types, and elements can be changed, added or removed after creation.

3.1 Slicing Worked Example (L = [1,2,3,4,5,6,7,8,9])

Expression Output Reading
L[0] / L[-1] 1 / 9 first / last
L[2:8] [3,4,5,6,7,8] index 2 through 7
L[1::2] [2,4,6,8] 2nd, 4th, 6th, 8th item
L[::2] [1,3,5,7,9] even indices (0,2,4,6,8)
L[4:] [5,6,7,8,9] from middle onward
L[-1:0:-1] [9,8,7,6,5,4,3,2] last down to second item
L[::-1] [9,8,7,6,5,4,3,2,1] full reverse

3.2 List Methods

Method Effect Example on L=[1,2]
append(x) add at end L.append(3) → [1,2,3]
insert(i,x) insert at index L.insert(0,9) → [9,1,2]
extend([x,y]) join another list L.extend([3,4])
remove(x) delete first matching value L.remove(2)
pop(i) remove and return L.pop() → 2
sort() / reverse() in-place ordering L.sort()
count(x) / index(x) query L.index(2) → 1
copy() / clear() duplicate / empty L.copy()

3.3 List Comprehension

Syntax: [expression for item in iterable if condition] — equivalent to a for loop with an optional filter, but written in one line.

squares = [i**2 for i in range(1, 6)]        # [1,4,9,16,25]
even_sq = [i**2 for i in [1,2,3,4,5] if i % 2 == 0]   # [4,16]
uniq = list(dict.fromkeys([1, 2, 2, 3]))     # [1,2,3] (removes duplicates)

Tiny tuple/list note: t = (1,) is a single-element tuple (comma required); x = ['12','hello',456]; x[0] *= 3 → '121212' (string repetition is legal), but x[1][1] = 'bye' raises TypeError because a string is immutable.

After-Topic PYQs:

  • 2023-24 (Sec C, 7 Marks): *"Illustrate different list slicing constructs for the following operations on the following list: L = [1, 2, 3, 4, 5, 6, 7, 8, 9]
  1. Return a list of numbers starting from the last to second item of the list
  2. Return a list that start from 3rd item to second last item.
  3. Return a list that has only even position elements of list L to list M.
  4. Return a list that starts from the middle of the list L.
  5. Return a list that reverses all the elements starting from element at index 0 to middle index only and return the entire list. Divide each element of the list by 2 and replace it with the remainder."*
  • 2025-26 (Sec A, 2 Marks): "What will be the output of the following Python code? def compute(x): return [i**2 for i in x if i%2==0] print(compute([1, 2, 3, 4, 5]))"
  • 2023-24 (Sec A, 2 Marks): "Describe the concept of list comprehension with a suitable example"
  • 2023-24 (Sec A, 2 Marks): *"Explain why the program generates an error. x = ['12', 'hello', 456] x[0] = 3 x[1][1] = 'bye'"

4. Tuples and Unpacking

Tuple: An immutable ordered sequence written in parentheses. Once created, elements cannot be changed, added or removed; tuples are hashable if their elements are hashable and are often used as dictionary keys and function return values.

t = (10, 20, 30)
print(t[1], t[-1])      # 20 30
print(t[1:])            # (20, 30)
print(t[::-1])          # (30, 20, 10)  ← reverse a tuple
a, b, c = t             # unpacking → 10, 20, 30
single = (5,)           # comma is required
Feature List Tuple
Syntax [1, 2] (1, 2)
Mutable Yes No
Methods append/pop/sort… only count(), index()
Hashable No Yes (if contents hashable)
Use changing collections fixed records, dict keys, multiple returns

After-Topic PYQs:

  • 2025-26 (Sec C, 7 Marks): "Discuss tuple and list slicing. Write a program to reverse a tuple."
  • 2025-26 (Sec C, 7 Marks): "Differentiate between List and Tuple in Python with suitable examples."
  • 2024-25 (Sec C, 7 Marks): "Describe how tuples differ from lists in Python with examples."
  • 2023-24 (Sec C, 7 Marks): "Illustrate Unpacking tuples, mutable sequences, and string concatenation with examples"
  • 2024-25 (Sec A, 2 Marks): "Demonstrate how to assign a single value to a tuple."

5. Dictionaries and CRUD Operations

Dictionary: An unordered-in-practice (ordered by insertion since Python 3.7) collection of key : value pairs. Keys must be unique and hashable; values may be any object.

d = {"roll": 21, "name": "Asha", "marks": 88}
print(d["name"])           # Read → Asha
print(d.get("phone", "NA"))  # safe read → NA
d["city"] = "Lucknow"      # Create/Update
d["marks"] = 92            # Update
del d["city"]              # Delete
d.pop("roll")              # Delete and return value
print(d.items(), d.keys(), d.values())

5.1 Built-in Dictionary Methods

Method Purpose
get(k, default) read safely without KeyError
keys() / values() / items() views of keys, values and pairs
update(other) merge another dict into this one
pop(k) / popitem() remove and return
setdefault(k, v) insert only if key absent
clear() / copy() empty / duplicate
fromkeys(seq, v) build dict from a sequence of keys

Merge two dictionaries:

d1 = {"a": 1, "b": 2}
d2 = {"b": 9, "c": 3}
d1.update(d2)        # in-place → {'a':1, 'b':9, 'c':3}

Since Python 3.9, merged = d1 | d2 also works; note the right-hand value wins for duplicate keys.

After-Topic PYQs:

  • 2025-26 (Sec A, 2 Marks): "Define dictionary in Python and give an example of its manipulation."
  • 2025-26 (Sec C, 7 Marks): "Explain list and dictionary in-built functions. Write a program to merge two dictionaries."
  • 2024-25 (Sec C, 7 Marks): "Write a program to demonstrate Create, Read, Update, and Delete (CRUD) operations on a dictionary."
  • 2024-25 (Sec C, 7 Marks): "Distinguish between a Tuple and a List with examples. Explain with examples at least 4 built-in methods of Dictionary."
  • 2023-24 (Sec C, 7 Marks): "Write a Python Program to find the sum all the items in a dictionary. For example if d = {'A': 100, 'B': 540, 'C': 239} then output should be 879."

6. Functions and Organising Code

Function: A named, reusable block of statements that accepts parameters and optionally returns a value. Functions remove duplication and let a large program be built from small tested pieces.

def area_circle(r):
    return 3.14159 * r * r

print(area_circle(5))
  • Definition: def name(param1, param2=default): with an indented body and optional return.
  • Call: pass arguments positionally or by keyword (area_circle(r=5)).
  • Scope: variables created inside a function are local; use global only when necessary.
  • Docstring: a triple-quoted first statement documenting the function.
  • Lambda: lambda args: expression — an anonymous one-expression function, handy with map(), filter() and comprehensions.
  • Modules: save functions in library.py, then use import library or from library import func in main.py (avoid running imports on a name collision).
c2f = lambda c: (c * 9/5) + 32
temps = [0, 20, 100]
print([c2f(c) for c in temps])   # [32.0, 68.0, 212.0]

After-Topic PYQs:

  • 2025-26 (Sec A, 2 Marks): "What are functions in Python?"
  • 2024-25 (Sec A, 2 Marks): "Briefly describe the use of lambda functions in Python."
  • 2025-26 (Sec C, 7 Marks): "Explain functions in Python. Write a function to calculate area of circle."
  • 2023-24 (Sec C, 7 Marks): "Explain the concept of functions in Python. Write a function that takes a list of numbers and returns the sum of all the numbers in the list."
  • 2023-24 (Sec C, 7 Marks): "Construct a function perfect_square(number) that returns a number if it is a perfect square otherwise it returns -1. For example: perfect_square(1) returns 1, perfect_square(2) returns -1"
  • 2023-24 (Sec C, 7 Marks): "Python function removenth(s, n) that takes as input a string and an integer n ≥ 0 and then removes a character at index n. If n is beyond the length of s, whole s is returned. For example: removenth("MANGO", 1) returns "MNGO"; removenth("MANGO", 3) returns "MANO""
  • 2023-24 (Sec C, 7 Marks): "Explain how lambda functions can be used within a list comprehension. Write a Python program that uses a lambda function within a list comprehension to convert a list of temperatures in Celsius to Fahrenheit."
  • 2023-24 (Sec A, 2 Marks): "How to use the functions defined in library.py in main.py"

Solved Exam-Ready Questions

Solved Q1 (2024-25, 2025-26 Sec C — 7 Marks | Survival Mode)

Q: Explain string slicing and string operations in Python.

Solution:

  • Definition: A string is an immutable sequence of characters; index 0 is the first character and −1 the last.
  • Slicing rule: s[start:stop:step] includes start, excludes stop; s[::-1] reverses. With s="PythonProgram": s[0:6]="Python", s[6:]="Program", s[::2]="PtoRm".
  • Operators: + concatenates, * repeats, in tests membership, len() counts characters.
  • Methods (with results): lower(), upper(), strip(), split(","), join(), replace(), find(), count().
  • Program: count vowels with sum(1 for c in s.lower() if c in "aeiou") or a loop; print the count.
  • Immutability note: s[0] = "J" raises TypeError; build a new string with concatenation or join() instead.

Solved Q2 (2023-24 Sec C — 7 Marks)

Q: *Illustrate different list slicing constructs for the following operations on the following list: L = [1, 2, 3, 4, 5, 6, 7, 8, 9]

  1. Return a list of numbers starting from the last to second item of the list
  2. Return a list that start from 3rd item to second last item.
  3. Return a list that has only even position elements of list L to list M.
  4. Return a list that starts from the middle of the list L.
  5. Return a list that reverses all the elements starting from element at index 0 to middle index only and return the entire list. Divide each element of the list by 2 and replace it with the remainder.*

Solution (trace each against L[0]=1 … L[8]=9):

  1. L[-1:0:-1] → [9,8,7,6,5,4,3,2] — walks from index 8 down to index 1 (the second item). If the second item is to be excluded, use L[-1:1:-1] → [9,8,7,6,5,4,3].
  2. Third item is index 2, second-last is index 7 (included) → L[2:8] → [3,4,5,6,7,8].
  3. Even positions (1-based: 2nd, 4th, 6th, 8th) → M = L[1::2] → [2,4,6,8]. If "even index" is intended, L[::2] → [1,3,5,7,9].
  4. Middle of nine elements is index 4 (value 5) → L[4:] → [5,6,7,8,9].
  5. Reverse indices 0 through 4 → [5,4,3,2,1]; replace each by remainder mod 2 → [1,0,1,0,1]; append the untouched tail → M = [x%2 for x in L[:5][::-1]] + L[5:] → [1,0,1,0,1,6,7,8,9]. If the division is intended for the whole list, [x%2 for x in L] → [1,0,1,0,1,0,1,0,1].
  • Examiner note: state the indexing convention used; ambiguity in "position" is common, so showing the slice and its output earns credit either way.

Solved Q3 (2024-25 Sec C — 7 Marks)

Q: Write a Python program to count the frequency of each character in a given string and return the output in a dictionary. Example: char_frequency("HELLO") returns {"H":1, "E":1, "L":2, "O":1}.

Solution:

def char_frequency(s):
    freq = {}
    for ch in s:
        freq[ch] = freq.get(ch, 0) + 1
    return freq

print(char_frequency("HELLO"))

Steps: create an empty dict → iterate each character → get(ch,0) returns 0 for a new key and the existing count otherwise → add one and store → return the dict. Output {'H': 1, 'E': 1, 'L': 2, 'O': 1}.


Solved Q4 (2025-26 Sec C — 7 Marks)

Q: Explain list and dictionary in-built functions. Write a program to merge two dictionaries.

Solution:

  • List built-ins: append, insert, extend, remove, pop, sort, reverse, count, index, copy, clear (give one example each for four of them).
  • Dictionary built-ins: get, keys, values, items, update, pop, popitem, setdefault, clear, copy, fromkeys.
  • Program:
d1 = {"a": 1, "b": 2, "c": 3}
d2 = {"b": 99, "d": 4}
d1.update(d2)
print("Merged:", d1)
  • Output: {'a': 1, 'b': 99, 'c': 3, 'd': 4} — update() adds new keys and overwrites existing keys with values from d2.
  • Alternative: merged = {**d1, **d2} or (Python 3.9+) merged = d1 | d2.

Solved Q5 (2025-26 Sec C — 7 Marks)

Q: Discuss tuple and list slicing. Write a program to reverse a tuple.

Solution:

  • Common slicing: both support seq[start:stop:step]; tuples return tuples and lists return lists.
  • Difference: lists are mutable and have many methods; tuples are immutable and support only count() and index().
  • Program:
t = (1, 2, 3, 4, 5)
r = t[::-1]
print("Original:", t)
print("Reversed:", r)
  • Output: (5, 4, 3, 2, 1). reversed(t) returns an iterator, so tuple(reversed(t)) is needed to obtain a tuple.
  • Unpacking note: a, b, c = (1,2,3) assigns three names in one statement.

Solved Q6 (2023-24 Sec C — 7 Marks)

Q: Explain the concept of functions in Python. Write a function that takes a list of numbers and returns the sum of all the numbers in the list.

Solution:

def sum_list(numbers):
    total = 0
    for x in numbers:
        total += x
    return total

nums = [10, 20, 30, 40]
print("Sum:", sum_list(nums))

Explanation: def creates the function, numbers is a local parameter, the loop accumulates into total, and return sends the result to the caller. Output Sum: 100. A built-in alternative is sum(numbers), but writing the loop demonstrates the algorithm.


Solved Q7 (2023-24 Sec C — 7 Marks)

Q: Construct a function perfect_square(number) that returns a number if it is a perfect square otherwise it returns -1. For example: perfect_square(1) returns 1, perfect_square(2) returns -1

Solution:

def perfect_square(number):
    if number < 0:
        return -1
    root = int(number ** 0.5)
    if root * root == number:
        return number
    return -1

print(perfect_square(1))    # 1
print(perfect_square(2))    # -1
print(perfect_square(144))  # 144

Reasoning: take the integer part of √number; a perfect square satisfies root*root == number. Negative numbers cannot be perfect squares in real integers, so return −1.


Solved Q8 (2023-24 Sec C — 7 Marks)

Q: Python function removenth(s, n) that takes as input a string and an integer n ≥ 0 and then removes a character at index n. If n is beyond the length of s, whole s is returned. For example: removenth("MANGO", 1) returns "MNGO"; removenth("MANGO", 3) returns "MANO"

Solution:

def removenth(s, n):
    if n >= len(s):          # beyond last index → unchanged
        return s
    return s[:n] + s[n+1:]   # join parts before and after index n

print(removenth("MANGO", 1))  # MNGO
print(removenth("MANGO", 3))  # MANO
print(removenth("MANGO", 9))  # MANGO

Trace: "MANGO" index 1 is A; "M" + "NGO" → "MNGO". Index 3 is G; "MAN" + "O" → "MANO".


Solved Q9 (2024-25 Sec C — 7 Marks)

Q: Write a program to demonstrate Create, Read, Update, and Delete (CRUD) operations on a dictionary.

Solution:

student = {}                          # empty dictionary
student["roll"] = 21                  # Create
student["name"] = "Asha"              # Create
student["marks"] = 88                 # Create
print("Read:", student["name"])       # Read
print("Safe read:", student.get("phone", "Not available"))
student["marks"] = 92                 # Update
del student["roll"]                   # Delete
removed = student.pop("name")         # Delete and return
print("Final:", student, "Removed:", removed)

Output: Read: Asha; Safe read: Not available; Final: {'marks': 92} Removed: Asha. Using get() avoids KeyError for absent keys.


Practice Questions (Self-Test)

  1. (2 Marks) What is the output of print([i**2 for i in [1,2,3,4,5] if i%2==0])? (Ans: [4, 16])
  2. (2 Marks) What is the output of print(list(filter(bool,[1,0,0,2,'hi','',[]])))? (Ans: [1, 2, 'hi'])
  3. (2 Marks) How do you assign a single value to a tuple? (Ans: t = (5,))
  4. (7 Marks) Write a function to find the longest word in a list of words and test it on ['apple','banana','cherry'].
  5. (7 Marks) Write a program that accepts comma-separated words, sorts them alphabetically and prints them comma-separated.
  6. (7 Marks) Write a function ret_smaller(l) that returns the smallest list from a nested list, breaking ties by first occurrence.
  7. (7 Marks) Demonstrate lambda inside a list comprehension by converting Celsius temperatures to Fahrenheit.