✦ VidyaVerseOpen interactive version

← Programming Concepts in Mechanical Engineering (25ME34I)

Data Structures: Lists, Tuples and Dictionaries

Programming Concepts in Mechanical Engineering (25ME34I) · C-25 Diploma Mechanical, Semester III

Read with diagrams, search and self-test

LEARNING OBJECTIVES

After studying this chapter you will be able to:

• Create lists and perform indexing, slicing, adding, removing and sorting.

• Use list methods and list comprehensions for engineering data.

• Explain tuples and their immutability, and use them to store fixed data such as coordinates.

• Create dictionaries and add, access, update and delete key-value pairs.

• Iterate over lists, tuples and dictionaries.

5.1 Introduction

A single variable holds one value. Engineering data, however, comes in groups: the diameters of 25 shafts, the coordinates of points on a cam profile, the properties of a material. A data structure stores a collection of values under one name so that they can be processed together. Python's main built-in data structures are the list, tuple, dictionary and set.

Fig. 5.1 List, tuple and dictionary at a glance

5.2 Lists

A list is an ordered, mutable (changeable) collection of items enclosed in square brackets and separated by commas. A list can hold items of different types and allows duplicates.

loads = [1200, 850, 1600, 975]            # list of integers
parts = ["bolt", "nut", "washer"]         # list of strings
mixed = ["EN8", 25.4, 3, True]            # mixed types
empty = []
print(loads, parts, mixed, empty, sep="\n")
print("Length of loads =", len(loads))
OUTPUT
[1200, 850, 1600, 975]
['bolt', 'nut', 'washer']
['EN8', 25.4, 3, True]
[]
Length of loads = 4

Indexing and slicing

Each item has an index: the first item is at index 0. Negative indices count from the end (−1 is the last item). Slicing list[start:stop:step] returns a new list from start up to, but not including, stop.

Fig. 5.2 Positive and negative indexing of a list

parts = ['bolt', 'nut', 'washer', 'rivet', 'pin']
print(parts[0], parts[2], parts[-1])
print(parts[1:4])      # index 1 to 3
print(parts[:2])       # first two
print(parts[3:])       # from index 3 to end
print(parts[::2])      # every second item
print(parts[::-1])     # reversed copy
OUTPUT
bolt washer pin
['nut', 'washer', 'rivet']
['bolt', 'nut']
['rivet', 'pin']
['bolt', 'washer', 'pin']
['pin', 'rivet', 'washer', 'nut', 'bolt']

Modifying a list

d = [25.02, 24.98, 25.01]
d[1] = 24.99                 # change an item
d.append(25.03)              # add at end
d.insert(0, 25.00)           # add at index 0
d.extend([24.97, 25.04])     # add many
print("After adding  :", d)
d.remove(25.03)              # remove first matching value
last = d.pop()               # remove and return last item
del d[0]                     # delete by index
print("After removing:", d, " popped:", last)
OUTPUT
After adding  : [25.0, 25.02, 24.99, 25.01, 25.03, 24.97, 25.04]
After removing: [25.02, 24.99, 25.01, 24.97]  popped: 25.04

List methods

MethodActionExample (L = [3, 1, 2])
append(x)Add x at the endL.append(5) → [3, 1, 2, 5]
insert(i, x)Insert x at index iL.insert(1, 9) → [3, 9, 1, 2]
extend(seq )Add all items of seqL.extend([7, 8])
remove(x)Remove first occurrence of xL.remove(1) → [3, 2]
pop(i)Remove and return item at i (last by default)L.pop() → 2
sort()Sort in place (reverse=True for descending)L.sort() → [1, 2, 3]
reverse()Reverse in placeL.reverse() → [2, 1, 3]
index(x)Index of first xL.index(2) → 2
count(x)Number of times x occursL.count(3) → 1
copy()Shallow copyM = L.copy()
clear()Remove all itemsL.clear() → []
hardness = [210, 185, 240, 198, 225, 185]
hardness.sort()
print("Ascending :", hardness)
hardness.sort(reverse=True)
print("Descending:", hardness)
print("185 occurs", hardness.count(185), "times;",
      "240 at index", hardness.index(240))
print("max, min, sum:", max(hardness), min(hardness), sum(hardness))
print("sorted() returns new list:", sorted([3, 1, 2]))
OUTPUT
Ascending : [185, 185, 198, 210, 225, 240]
Descending: [240, 225, 210, 198, 185, 185]
185 occurs 2 times; 240 at index 0
max, min, sum: 240 185 1243
sorted() returns new list: [1, 2, 3]

Operations on lists

a = [1, 2]; b = [3, 4]
print(a + b, a * 3, 3 in b, 5 not in b)
OUTPUT
[1, 2, 3, 4] [1, 2, 1, 2, 1, 2] True True

Iterating over a list

temps = [72.5, 75.1, 78.4, 74.0]
for t in temps:
    print(t, end="  ")
print()
for i, t in enumerate(temps, start=1):
    print(f"Reading {i}: {t} °C")
OUTPUT
72.5  75.1  78.4  74.0
Reading 1: 72.5 °C
Reading 2: 75.1 °C
Reading 3: 78.4 °C
Reading 4: 74.0 °C

List comprehension

A list comprehension builds a new list in one readable line: [expression for item in iterable if condition].

loads_kN = [5, 10, 15, 20]
loads_N = [x * 1000 for x in loads_kN]
stress = [round(P / 78.5, 1) for P in loads_N]
high = [s for s in stress if s > 150]
print(loads_N, stress, high, sep="\n")
OUTPUT
[5000, 10000, 15000, 20000]
[63.7, 127.4, 191.1, 254.8]
[191.1, 254.8]

Nested lists (2-D data, matrices)

# 3 samples x 4 readings of diameter
data = [[25.01, 24.99, 25.02, 25.00],
        [24.98, 25.00, 25.01, 24.99],
        [25.03, 25.01, 25.00, 25.02]]
print("Sample 2, reading 3 =", data[1][2])
for k, s in enumerate(data, 1):
    print(f"Sample {k}: mean = {sum(s)/len(s):.4f}")
OUTPUT
Sample 2, reading 3 = 25.01
Sample 1: mean = 25.0050
Sample 2: mean = 24.9950
Sample 3: mean = 25.0150

5.3 Tuples

A tuple is an ordered, immutable collection enclosed in round brackets. Once created, its items cannot be changed, added or removed. Tuples are used for fixed data: coordinates, standard sizes, RGB colours, records that must not be altered.

point = (3.0, 4.5)              # 2-D coordinate
std_bolts = ("M6", "M8", "M10", "M12")
single = (5,)                   # single-item tuple needs a comma
print(point[0], std_bolts[-1], std_bolts[1:3], type(single))
x, y = point                    # tuple unpacking
print("x =", x, " y =", y)
print(std_bolts.count("M8"), std_bolts.index("M10"))
try:
    point[0] = 7.0
except TypeError as e:
    print("Error:", e)
OUTPUT
3.0 M12 ('M8', 'M10') <class 'tuple'>
x = 3.0  y = 4.5
1 2
Error: 'tuple' object does not support item assignment

Why tuples? (Advantages of immutability)

• Data safety: constant data (standard sizes, material constants) cannot be changed by mistake.

• Faster and use less memory than lists.

• Can be used as dictionary keys (lists cannot).

• Functions return multiple values as tuples.

List vs Tuple

ListTuple
Square brackets [ ]Round brackets ( )
Mutable – items can be changedImmutable – cannot be changed
Many methods (append, remove, sort...)Only count() and index()
Slower, more memoryFaster, less memory
Cannot be a dictionary keyCan be a dictionary key
For data that changes (readings)For fixed data (coordinates, constants)

5.4 Dictionaries

A dictionary stores data as key : value pairs inside curly braces. Values are accessed by key, not by position. Keys must be unique and immutable (string, number, tuple); values can be anything. Since Python 3.7, dictionaries remember insertion order.

steel = {"name": "EN8", "E": 200000, "yield": 350, "density": 7850}
print(steel["name"], steel["yield"])          # access by key
print(steel.get("UTS", "not available"))      # safe access
steel["UTS"] = 600                            # add new pair
steel["yield"] = 380                          # update value
del steel["density"]                          # remove pair
removed = steel.pop("E")                      # remove & return
print(steel, " removed E =", removed)
print("'UTS' in steel?", "UTS" in steel)
OUTPUT
EN8 350
not available
{'name': 'EN8', 'yield': 380, 'UTS': 600}  removed E = 200000
'UTS' in steel? True

Dictionary methods

MethodAction
d[key]Value for key (KeyError if absent)
d.get(key, default)Value or default if absent
d[key] = valueAdd or update
d.update(other)Add/update many pairs
d.pop(key)Remove key and return its value
del d[key]Delete key
d.keys(), d.values(), d.items()Views of keys, values, pairs
d.clear()Remove all items
len(d)Number of pairs

Iterating over a dictionary

E = {"Steel": 200, "Cast iron": 100, "Aluminium": 70, "Copper": 117}
for material in E:
    print(material, end=", ")
print()
for material, value in E.items():
    print(f"{material:<10} E = {value} GPa")
print("Stiffest:", max(E, key=E.get))
OUTPUT
Steel, Cast iron, Aluminium, Copper,
Steel      E = 200 GPa
Cast iron  E = 100 GPa
Aluminium  E = 70 GPa
Copper     E = 117 GPa
Stiffest: Steel

Nested dictionaries

machines = {
    "L01": {"type": "Lathe", "power": 5.5, "status": "running"},
    "M02": {"type": "Milling", "power": 7.5, "status": "idle"},
}
for mid, info in machines.items():
    print(mid, info["type"], info["power"], "kW", info["status"])
OUTPUT
L01 Lathe 5.5 kW running
M02 Milling 7.5 kW idle

5.5 Sets (for reference)

A set is an unordered collection of unique items, {1, 2, 3}. It removes duplicates automatically and supports union |, intersection & and difference -.

defects_shift1 = {"crack", "burr", "porosity"}
defects_shift2 = {"burr", "dent"}
print(defects_shift1 | defects_shift2)
print(defects_shift1 & defects_shift2)
print(sorted(set([3, 1, 3, 2, 1])))
OUTPUT
{'crack', 'dent', 'burr', 'porosity'}
{'burr'}
[1, 2, 3]

5.6 Comparison of Data Structures

FeatureListTupleDictionarySet
Brackets[ ]( ){ key: value }{ }
OrderedYesYesYes (3.7+)No
MutableYesNoYesYes
DuplicatesAllowedAllowedKeys uniqueNot allowed
AccessIndexIndexKeyMembership only

5.7 Practice Programs (Week 5)

Program 5.1 – Student names: add, remove and sort

# Program 5.1: List operations on student names
students = []
n = int(input("How many students? "))
for i in range(n):
    students.append(input(f"Name {i+1}: "))
print("List          :", students)
students.append(input("Name to add   : "))
print("After adding  :", students)
name = input("Name to remove: ")
if name in students:
    students.remove(name)
    print("After removing:", students)
else:
    print(name, "not found")
students.sort()
print("Sorted A-Z    :", students)
students.sort(reverse=True)
print("Sorted Z-A    :", students)
print("Total students:", len(students))
OUTPUT
How many students? 4
Name 1: Ravi
Name 2: Anitha
Name 3: Kiran
Name 4: Deepa
List          : ['Ravi', 'Anitha', 'Kiran', 'Deepa']
Name to add   : Manoj
After adding  : ['Ravi', 'Anitha', 'Kiran', 'Deepa', 'Manoj']
Name to remove: Kiran
After removing: ['Ravi', 'Anitha', 'Deepa', 'Manoj']
Sorted A-Z    : ['Anitha', 'Deepa', 'Manoj', 'Ravi']
Sorted Z-A    : ['Ravi', 'Manoj', 'Deepa', 'Anitha']
Total students: 4

Program 5.2 – Convert a list of temperatures from Celsius to Fahrenheit

F=C×9/5+32

# Program 5.2: Celsius list to Fahrenheit
celsius = [0, 25, 37, 60, 100, -40]
fahrenheit = []
for c in celsius:
    fahrenheit.append(c * 9 / 5 + 32)
print("Celsius   :", celsius)
print("Fahrenheit:", fahrenheit)
# same using list comprehension
print("Using comprehension:", [c * 9/5 + 32 for c in celsius])
print(f"{'°C':>6} {'°F':>7}")
for c, f in zip(celsius, fahrenheit):
    print(f"{c:6} {f:7.1f}")
OUTPUT
Celsius   : [0, 25, 37, 60, 100, -40]
Fahrenheit: [32.0, 77.0, 98.6, 140.0, 212.0, -40.0]
Using comprehension: [32.0, 77.0, 98.6, 140.0, 212.0, -40.0]
    °C      °F
     0    32.0
    25    77.0
    37    98.6
    60   140.0
   100   212.0
   -40   -40.0

Program 5.3 – Student records in a dictionary with add/remove functions

# Program 5.3: Student records using a dictionary
records = {}
def add_student(reg, name, age, grade):
    records[reg] = {"name": name, "age": age, "grade": grade}
    print("Added", reg)
def remove_student(reg):
    if reg in records:
        del records[reg]
        print("Removed", reg)
    else:
        print(reg, "not found")
def show():
    print(f"{'Reg':<6}{'Name':<10}{'Age':<5}{'Grade'}")
    for r, s in records.items():
        print(f"{r:<6}{s['name']:<10}{s['age']:<5}{s['grade']}")
while True:
    ch = input("1-Add 2-Show 3-Remove 4-Exit: ")
    if ch == "1":
        reg = input("Reg no: ")
        nm = input("Name  : ")
        ag = int(input("Age   : "))
        gr = input("Grade : ")
        add_student(reg, nm, ag, gr)
    elif ch == "2":
        show()
    elif ch == "3":
        remove_student(input("Reg no to remove: "))
    elif ch == "4":
        print("Bye")
        break
OUTPUT
1-Add 2-Show 3-Remove 4-Exit: 1
Reg no: 101
Name  : Ravi
Age   : 19
Grade : A
Added 101
1-Add 2-Show 3-Remove 4-Exit: 1
Reg no: 102
Name  : Anitha
Age   : 18
Grade : A+
Added 102
1-Add 2-Show 3-Remove 4-Exit: 3
Reg no to remove: 101
Removed 101
1-Add 2-Show 3-Remove 4-Exit: 2
Reg   Name      Age  Grade
102   Anitha    18   A+
1-Add 2-Show 3-Remove 4-Exit: 4
Bye

Program 5.4 – Coordinates in 2D space using tuples

# Program 5.4: Tuples for 2-D coordinates
import math
points = [(0, 0), (40, 0), (40, 30), (0, 30)]   # plate corners
print("Corner coordinates of plate:")
for i, (x, y) in enumerate(points, start=1):
    print(f"  P{i} = ({x}, {y})")
# distance between first and third point (diagonal)
(x1, y1), (x3, y3) = points[0], points[2]
diag = math.hypot(x3 - x1, y3 - y1)
print("Diagonal length =", diag, "mm")
# perimeter by walking around the polygon
per = 0
for i in range(len(points)):
    xa, ya = points[i]
    xb, yb = points[(i + 1) % len(points)]
    per += math.hypot(xb - xa, yb - ya)
print("Perimeter =", per, "mm")
OUTPUT
Corner coordinates of plate:
  P1 = (0, 0)
  P2 = (40, 0)
  P3 = (40, 30)
  P4 = (0, 30)
Diagonal length = 50.0 mm
Perimeter = 140.0 mm

Program 5.5 – Statistics of shaft diameters stored in a list

d = [25.02, 24.98, 25.01, 25.00, 24.99, 25.03, 24.97]
n = len(d)
mean = sum(d) / n
rng = max(d) - min(d)
var = sum((x - mean) ** 2 for x in d) / (n - 1)
print(f"n = {n}, mean = {mean:.4f}, range = {rng:.2f}")
print(f"variance = {var:.6f}, std dev = {var**0.5:.5f}")
print("Rejected (outside 25 ± 0.02):",
      [x for x in d if not 24.98 <= x <= 25.02])
OUTPUT
n = 7, mean = 25.0000, range = 0.06
variance = 0.000467, std dev = 0.02160
Rejected (outside 25 ± 0.02): [25.03, 24.97]

Program 5.6 – Material property lookup

props = {"steel": (200, 7850), "aluminium": (70, 2700),
         "copper": (117, 8960), "brass": (100, 8500)}
m = input("Material: ").lower()
if m in props:
    E, rho = props[m]
    print(f"{m.title()}: E = {E} GPa, density = {rho} kg/m^3")
else:
    print("Material not in table:", list(props.keys()))
OUTPUT
Material: aluminium
Aluminium: E = 70 GPa, density = 2700 kg/m^3

5.8 Solved Exam Questions

Q1. What is a list? Explain indexing and slicing with examples. (6 marks)

Answer: A list is an ordered, mutable collection enclosed in [ ]. Indexing accesses one item: L[0] first, L[-1] last. Slicing L[start:stop:step] gives a sub-list from start to stop−1. Example with parts = ['bolt','nut','washer','rivet','pin']: parts[1:4] → ['nut','washer','rivet'], parts[::-1] → reversed list. See Fig. 5.2.

Q2. Explain any five list methods with examples. (5 marks)

Answer: append(), insert(), remove(), pop(), sort() – see the table in Section 5.2 and the programs.

Q3. What is a tuple? Why is it called immutable? Compare tuple with list. (6 marks)

Answer: A tuple is an ordered collection in ( ) whose items cannot be changed after creation; assignment like t[0] = 5 raises TypeError, hence immutable. See the comparison table in Section 5.3. Tuples suit fixed data such as coordinates and standard sizes.

Q4. Explain dictionary with creation, access, adding and removing of key-value pairs. (6 marks)

Answer: A dictionary stores key:value pairs in { }. Create: d = {"E": 200, "G": 80}; access: d["E"] or d.get("E"); add/update: d["nu"] = 0.3; remove: del d["G"] or d.pop("G"). Iterate with for k, v in d.items(). See Section 5.4.

Q5. Differentiate between list, tuple and dictionary.

Answer: See the table in Section 5.6.

5.9 Multiple Choice Questions

1. Which of the following is a mutable data structure? a) Tuple b) String c) List d) Integer

Answer: (c) Reason: List items can be changed, added and removed after creation.

2. If L = [10, 20, 30, 40], L[-1] is a) 10 b) 40 c) 30 d) Error

Answer: (b) Reason: Negative index −1 refers to the last item.

3. L = [10, 20, 30, 40, 50]; L[1:3] gives a) [10, 20, 30] b) [20, 30] c) [20, 30, 40] d) [30, 40]

Answer: (b) Reason: The slice includes index 1 and 2 but stops before 3.

4. Which method adds an item at the end of a list? a) add() b) insert() c) append() d) extend()

Answer: (c) Reason: append() adds one item at the end; extend() adds several.

5. Which brackets are used to create a tuple? a)[] b){} c)() d)<>

Answer: (c) Reason: Tuples use round brackets; a single-item tuple needs a trailing comma.

6. t = (1, 2, 3); t[0] = 9 results in a) (9, 2, 3) b) TypeError c) [9, 2, 3] d) None

Answer: (b) Reason: Tuples are immutable; item assignment is not supported.

7. Dictionary values are accessed using a) index b) key c) slice d) position

Answer: (b) Reason: Each value is retrieved through its unique key.

8. Which statement deletes the key "E" from dictionary d? a) d.remove("E") b) del d["E"] c) d.delete("E") d) d.discard("E")

Answer: (b) Reason: del with the key removes the pair; pop("E") also works.

9. d.get("UTS", 0) returns 0 when a) UTS value is 0 b) key UTS is absent c) always d) never

Answer: (b) Reason: get() returns the default when the key does not exist, avoiding KeyError.

10. len({"a": 1, "b": 2, "c": 3}) is a)6 b)3 c) 2 d) Error

Answer: (b) Reason: len() counts the key-value pairs.

11. Which data structure removes duplicates automatically? a) list b) tuple c) set d) dictionary values

Answer: (c) Reason: A set stores only unique elements.

12. [x*2 for x in range(3)] gives a) [0, 2, 4] b) [2, 4, 6] c) [0, 1, 2] d) [1, 2, 3]

Answer: (a) Reason: range(3) is 0, 1, 2; each doubled.

13. Which can be used as a dictionary key? a) list b) tuple c) dictionary d) set

Answer: (b) Reason: Keys must be immutable (hashable); a tuple qualifies.

14. L = [3, 1, 2]; L.sort() returns a) [1, 2, 3] b) None (L is sorted in place) c) [3, 2, 1] d) Error

Answer: (b) Reason: sort() modifies the list and returns None; sorted(L) returns a new list.

15. d.items() returns a) only keys b) only values c) key-value pairs d) number of items

Answer: (c) Reason: items() gives (key, value) pairs, used in for k, v in d.items().

5.10 Exercises

1. Store the hardness values of 10 specimens in a list; find the average, maximum and the specimens below 200 BHN.

2. Create a dictionary of five machines with their power ratings; print the total connected load.

3. Store the vertices of a triangle as tuples and compute its area using the shoelace formula.

4. Write a program to merge two lists of part numbers and remove duplicates.

5. Create a dictionary that maps gear names to (teeth, module) tuples and print the pitch circle diameter of each.