ACS101 · Programming Languages · Unit 5
Python Data Structures and Emerging Applications
Unit Scope & Exam Weightage: This unit turns basic Python into practical data work: Python list, tuple, dictionary, set — basic operations only, File handling — read and write a text file, read a CSV (2–3 lines), Introduction to NumPy — array, mean, simple arithmetic, Introduction to Matplotlib — plot a simple line graph, and One mini-demo — IoT sensor simulation. No genuine PYQ cluster is attached, so the questions below are labelled predicted and are built directly from these syllabus items and the week 11–15 tutorial problems. This unit also contains the week-by-week practice set; use the Python rows as a revision checklist.
Front Page: Importance-Wise Topic Roadmap (Predicted from Syllabus)
| Priority | Topic (Exact Syllabus) | PYQs Asked | Marks Weightage | Tag |
|---|---|---|---|---|
| 1 | Python list / tuple / dictionary / set — basic operations only | 0 genuine PYQs | predicted 7m + 2m | Predicted Program |
| 2 | File handling — read and write a text file / read a CSV (2–3 lines) | 0 genuine PYQs | predicted 7m | Predicted Program |
| 3 | Introduction to NumPy — array / mean / simple arithmetic (5 lines) | 0 genuine PYQs | predicted 7m | Predicted Numerical |
| 4 | Introduction to Matplotlib — plot a simple line graph (5 lines) | 0 genuine PYQs | predicted 7m | Predicted Program |
| 5 | One mini-demo — IoT sensor simulation Real connect: Python lists power NumPy which powers TensorFlow | 0 genuine PYQs | predicted 7m | Predicted Demo |
| 6 | Matplotlib plots are used in every engineering report and data science notebook | integrated in #4 | — | Real Connect |
| 7 | This unit opens the door to AI, IoT, and Data Science using the same Python basics learnt in Unit IV | integrated in #1–#5 | — | Real Connect |
| 8 | Tutorial Hour — Week-by-Week Practice Problems (Python weeks 11–15) | 0 genuine PYQs | tutorial set | Practice Checklist |
2-Hour Last-Night Survival Checklist:
- Pick the right container: list = ordered mutable (
[1,2]), tuple = ordered immutable ((1,2)), dictionary = key→value ({"roll":21}), set = unique unordered ({1,2}). One line each secures a 2-mark definition. - CSV in Python: use the
csvmodule withopen(file, newline="")andcsv.reader; skip the header withnext(reader). Do not split manually when quotes may appear. - NumPy five lines:
import numpy as np,a = np.array([...]),a.mean(),a * 2,print(...).Know thata * 2multiplies every element, unlike list multiplication which repeats the list. - Matplotlib five lines:
import matplotlib.pyplot as plt,plt.plot(x,y),plt.xlabel,plt.ylabel,plt.show(). Addplt.titleif space allows. - IoT demo shape: generate a list of 5 temperature readings, convert with
np.array, computemean(), print readings and plot them against sample index. This one template answers list, NumPy and Matplotlib questions together.
1. Python Data Structures: List, Tuple, Dictionary, Set
Container choice: Python provides four built-in containers for basic work. A list is ordered and mutable; a tuple is ordered and immutable; a dictionary maps hashable keys to values; a set stores unique values and supports union/intersection.
| Container | Literal | Mutable? | Ordered? | Basic operation | Example result |
|---|---|---|---|---|---|
| list | [10, 20, 30] |
Yes | Yes | a[1], a.append(40), max(a) |
20, list with 40, 30 |
| tuple | (10, 20, 30) |
No | Yes | t[0], len(t) |
10, 3 |
| dictionary | {"roll":21, "marks":88.5} |
Yes | insertion (3.7+) | d["marks"], d.keys() |
88.5, keys view |
| set | {1, 2, 2, 3} |
Yes | No | len(s), s.add(4), s & t |
3, adds 4, intersection |
marks = [88, 92, 79, 85, 90]
print("Max:", max(marks), "Min:", min(marks), "Avg:", sum(marks)/len(marks))
student = ("Asha", 21, 88.5) # tuple: name, roll, marks
record = {"name": "Asha", "roll": 21, "marks": 88.5}
print(record["name"], student[2])
unique = {1, 2, 2, 3, 3} # {1, 2, 3}
print(len(unique)) # 3
List slicing: a[1:3] returns elements at indices 1 and 2; a[::-1] reverses the list. Dictionary update: d["city"] = "Lucknow" adds or replaces a key. Set duplicate removal: list(set([1,2,2,3])) gives [1,2,3] with unspecified order.
%%{init: {'theme': 'base', 'look': 'handDrawn', 'themeVariables': {'fontFamily': "'Nunito', sans-serif", 'fontSize': '17px', 'primaryColor': '#EFEAD6', 'primaryBorderColor': '#0F766E', 'lineColor': '#23211C'}}}%%
flowchart TD
A["Sensor readings"] --> B["Python list<br/>ordered, editable"]
B --> C["NumPy array<br/>vector arithmetic + mean"]
C --> D["Matplotlib line graph"]
B --> E["Dictionary<br/>name → value pairs"]
B --> F["Set<br/>unique device IDs"]
C --> G["AI / IoT / Data Science"]
Examiner Tip: When asked to compare list and tuple, include the memory/performance reason: tuples cannot be changed, so Python can store them more compactly and use them as dictionary keys. This earns the “why” mark beyond the definition.
2. File Handling: Text File and CSV
Text file handling in Python uses open(filename, mode) with modes r, w, a, and the recommended with statement, which closes the file automatically even if an error occurs.
# write a text file
with open("records.txt", "w") as f:
f.write("Asha 88.5\n")
f.write("Ravi 91.0\n")
# read and display it
with open("records.txt", "r") as f:
for line in f:
print(line.strip())
Reading a CSV (2–3 lines):
import csv
with open("marks.csv", newline="") as f:
reader = csv.reader(f)
header = next(reader) # skip column names
for row in reader: # 2–3 data rows in the exam file
print(row[0], row[1])
For marks.csv containing name,marks then Asha,88.5 and Ravi,91.0, the output is Asha 88.5 and Ravi 91.0. Use float(row[1]) before computing an average.
| Python | C (Unit 3 recall) |
|---|---|
open("f","w") |
fopen("f","w") |
with auto-closes |
explicit fclose(fp) required |
for line in f |
while (fgets(...)) |
csv.reader(f) |
manual tokenisation with strtok |
3. Introduction to NumPy: Array, Mean, Simple Arithmetic
NumPy array: an ndarray is a homogeneous, fixed-size array stored contiguously, so elementwise arithmetic is implemented in optimised C loops. a.mean() returns the arithmetic mean of all elements.
import numpy as np
a = np.array([10, 20, 30, 40, 50])
print(a) # [10 20 30 40 50]
print(a.mean()) # 30.0
print(a + 5) # [15 25 35 45 55]
print(a * 2) # [20 40 60 80 100]
print(a ** 2) # [100 400 900 1600 2500]
| Operation | Python list | NumPy array |
|---|---|---|
x * 2 |
repeats the list: [1,2,1,2] |
multiplies each element: [2,4] |
x + 5 |
error | adds 5 to each element |
| Mean | sum(x)/len(x) |
x.mean() |
| Speed | Python-level loop | vectorised C implementation |
The array may also be two-dimensional: np.array([[1,2],[3,4]]) has shape (2,2); a.mean(axis=0) averages down columns giving [2.0, 3.0], while a.mean(axis=1) averages across rows giving [1.5, 3.5].
4. Introduction to Matplotlib: Simple Line Graph
Matplotlib is Python's plotting library. plt.plot(x, y) draws a line graph from two equal-length sequences; labels and plt.show() complete the five-line exam program.
import matplotlib.pyplot as plt
x = [1, 2, 3, 4, 5]
y = [22, 24, 21, 26, 25]
plt.plot(x, y, marker="o")
plt.xlabel("Sample number")
plt.ylabel("Temperature (°C)")
plt.title("IoT temperature readings")
plt.show()
| Function | Role | Exam credit |
|---|---|---|
plt.plot(x,y) |
Draws line through points | Core mark |
plt.xlabel / plt.ylabel |
Axis labels | Presentation mark |
plt.title |
Graph title | Presentation mark |
plt.grid(True) |
Adds grid lines | Optional |
plt.show() |
Renders the figure | Required to see output |
In a notebook (Google Colab), the plot appears inline; in a local script, plt.show() opens a window.
5. Mini-Demo: IoT Sensor Simulation and Real Connect
IoT sensor simulation: generate a short series of readings in Python, convert to a NumPy array for arithmetic, and plot with Matplotlib. This single demo exercises list, NumPy, and plotting in the order stated in the syllabus.
import numpy as np
import matplotlib.pyplot as plt
temps = [23.5, 24.1, 22.8, 25.0, 26.2] # simulated sensor readings
arr = np.array(temps)
print("Readings:", arr)
print("Mean temperature:", round(arr.mean(), 2))
print("Deviation from mean:", np.round(arr - arr.mean(), 2))
plt.plot(range(1, 6), arr, marker="o")
plt.xlabel("Sample")
plt.ylabel("°C")
plt.show()
For these readings, arr.mean() = 24.32, and the deviations are [-0.82, -0.22, -1.52, 0.68, 1.88]. The same list → array → plot chain is how a data-science notebook turns raw sensor data into a report figure.
Real connect: Python lists power NumPy; NumPy arrays power TensorFlow and other ML libraries; Matplotlib figures appear in every engineering report. The basics learned in Unit 4 (loops, functions, if) are reused unchanged here.
6. Tutorial Hour — Week-by-Week Practice Checklist (Python Rows)
| Week | Language | Tutorial problems from the syllabus |
|---|---|---|
| 11 | Python | Hello World in Python; BMI calculator; Temperature converter (°C → °F); Compare C vs Python syntax |
| 12 | Python | Grade calculator in Python; Fibonacci using Python loop; Simple calculator using functions in Python |
| 13 | Python | List: marks of 5 students → max, min, average; Dictionary: store name and marks of 3 students; Count word frequency in a sentence |
| 14 | Python | Write student records to a text file; Read and display the file; Read a small CSV and print rows |
| 15 | Python | NumPy: create array, compute mean; Matplotlib: plot a line graph of marks; Mini-demo: simulate 5 IoT temperature readings and plot |
The syllabus also states that students use Google Colab for Python (no installation needed) while C uses GCC/Code::Blocks, and that tutorial hour is compulsory hands-on coding. These rows are the minimum set; the teacher may add variants.
7. Predicted Exam-Ready Questions (Solved — Not Verbatim PYQs)
Predicted Q1 (7 Marks | List, Dictionary, Set)
Q (predicted from “Python list / tuple / dictionary / set — basic operations only”): Store marks of five students in a list, print maximum, minimum and average. Also create a dictionary of three students' names and marks, and a set of five sensor IDs containing one duplicate; print the set size.
Solution:
marks = [88, 92, 79, 85, 90]
print("Max:", max(marks)) # 92
print("Min:", min(marks)) # 79
print("Average:", sum(marks)/len(marks)) # 86.8
students = {"Asha": 88, "Ravi": 92, "Neha": 79}
for name, m in students.items():
print(name, m)
ids = {11, 12, 12, 13, 14}
print("Unique IDs:", ids, "Count:", len(ids)) # {11,12,13,14}, 4
max/min/sum/len are list built-ins; items() iterates key–value pairs; the set automatically removed the repeated 12.
Predicted Q2 (7 Marks | Text File and CSV)
Q (predicted from “File handling — read and write a text file, read a CSV (2–3 lines)”): Write a Python program to write three student names to students.txt, read the file back and print each line. Then read marks.csv with columns name,marks and print each row.
Solution:
with open("students.txt", "w") as f:
for name in ["Asha", "Ravi", "Neha"]:
f.write(name + "\n")
with open("students.txt", "r") as f:
for line in f:
print(line.strip())
import csv
with open("marks.csv", newline="") as f:
reader = csv.reader(f)
next(reader) # skip header
for row in reader: # 2–3 lines
print(row[0], float(row[1]))
The with block closes each file automatically. strip() removes the trailing newline before printing; newline="" is recommended for CSV on Windows.
Predicted Q3 (7 Marks | NumPy and Matplotlib)
Q (predicted from “Introduction to NumPy — array, mean, simple arithmetic” and “Introduction to Matplotlib — plot a simple line graph”): Create a NumPy array of marks [65, 72, 80, 68, 91]. Print the array, its mean, the array after adding 5 grace marks, and plot the original marks against student number.
Solution:
import numpy as np
import matplotlib.pyplot as plt
marks = np.array([65, 72, 80, 68, 91])
print("Original:", marks)
print("Mean:", marks.mean())
grace = marks + 5
print("With grace:", grace)
plt.plot(range(1, 6), marks, marker="o")
plt.xlabel("Student number")
plt.ylabel("Marks")
plt.title("Marks after test")
plt.show()
Mean = (65+72+80+68+91)/5 = 376/5 = 75.2. Grace marks array is [70 77 85 73 96]. Elementwise addition is the NumPy behaviour; a plain Python list would not support marks + 5.
Predicted Q4 (2 Marks | Container Identification)
Q (predicted from “Python list, tuple, dictionary, set — basic operations only”): Which container would you use for (i) marks that will be updated, (ii) a fixed roll-number triple, (iii) name→marks lookup? Give one reason each.
Solution: (i) list, because elements can be appended/changed by index; (ii) tuple, because the values must not change and can be used as a key; (iii) dictionary, because lookup by key name is O(1) on average and reads naturally as d[name].
8. Practice Questions (Self-Test)
- (2 Marks) What is the difference between
a * 2for a list and for a NumPy array? - (7 Marks) Read a sentence and count word frequency using a dictionary. (Hint:
for w in s.split(): d[w] = d.get(w,0)+1.) - (7 Marks) Write a program that appends three names to a text file, then reads and prints the last line only.
- (7 Marks) Generate five random temperature values between 20 and 30, compute their NumPy mean, and print values above the mean.
- (7 Marks) Plot two lines on one graph (marks before and after grace) with a legend and axis labels.