Chapter 10: Tuples and Dictionaries
10.1 Introduction to Tuples
In earlier chapters, we learned that programs often need to store multiple values together. Lists are one such data structure. However, not all collections of data should be changeable.
Consider these examples:
- Days of the week
- Dimensions of a rectangle
- Coordinates of a point
- RGB values of a color
In such cases:
- The values are related
- The values should not change accidentally
Python provides tuples for exactly this purpose.
A tuple is a collection of elements that is:
- ordered
- indexed
- immutable (cannot be changed)
10.2 Tuple Operations
Creating a Tuple
Tuples are created by placing values inside parentheses ().
t = (10, 20, 30)
print(t)
A tuple can store different data types:
info = ("Amit", 11, 85.5)
Tuple with One Element (Important Detail)
To create a tuple with one element, a trailing comma is mandatory.
t1 = (5)
print(type(t1)) # int
t2 = (5,)
print(type(t2)) # tuple
Why?
- Without comma, Python treats it as a normal expression
- The comma defines the tuple, not the parentheses
Accessing Tuple Elements (Indexing)
Tuples use zero-based indexing, just like strings and lists.
t = (10, 20, 30, 40)
print(t[0]) # 10
print(t[-1]) # 40
Slicing a Tuple
t = (10, 20, 30, 40, 50)
print(t[1:4])
print(t[:3])
print(t[::2])
Slicing always returns a new tuple.
Immutability of Tuples (Core Concept)
Once created, tuple elements cannot be modified.
t = (10, 20, 30)
t[0] = 100 # ❌ TypeError
Why Python enforces this:
- Data safety
- Faster processing
- Suitable for fixed collections
Tuple Concatenation and Repetition
t1 = (1, 2)
t2 = (3, 4)
print(t1 + t2)
print(t1 * 3)
Membership Operators
t = (10, 20, 30)
print(20 in t)
print(50 not in t)
10.3 Tuple Methods and Built-in Functions
Since tuples are immutable, they provide very few methods.
Tuple Methods
t = (10, 20, 20, 30)
print(t.count(20))
print(t.index(30))
Built-in Functions on Tuples
t = (5, 2, 9, 1)
print(len(t))
print(max(t))
print(min(t))
print(sum(t))
print(sorted(t)) # returns list
Note:
sorted()returns a list, not a tuple
10.4 Tuple Assignment
Python allows assigning multiple variables in a single statement using tuples.
a, b, c = (10, 20, 30)
print(a)
print(b)
print(c)
This is called tuple unpacking.
Swapping Values Using Tuples
x = 5
y = 10
x, y = y, x
print(x, y)
No temporary variable required — this is a Python feature.
10.5 Nested Tuples
A tuple can contain another tuple.
t = (1, 2, (3, 4), 5)
Accessing nested elements:
print(t[2])
print(t[2][0])
print(t[2][1])
Nested tuples are useful for:
- structured records
- coordinates
- fixed tabular data
10.6 Tuple Handling
This section focuses on practical tuple processing.
Example 1: Counting Even Numbers
t = (10, 15, 20, 25, 30)
count = 0
for num in t:
if num % 2 == 0:
count += 1
print("Even numbers:", count)
Example 2: Finding Maximum Without Built-in
t = (12, 45, 23, 67, 34)
max_val = t[0]
for num in t:
if num > max_val:
max_val = num
print("Maximum:", max_val)
10.7 Introduction to Dictionaries
While tuples store data using positions (index), many real-world problems require data to be stored using meaningful names.
Example:
- Student name → marks
- Roll number → details
- Word → meaning
Python provides dictionaries for such data.
A dictionary:
- stores data as key–value pairs
- is unordered
- is indexed by keys, not numbers
- is mutable
10.8 Dictionaries are Mutable
Creating a Dictionary
student = {
"name": "Amit",
"class": 11,
"marks": 85
}
Accessing Values Using Keys
print(student["name"])
print(student["marks"])
Modifying Values
student["marks"] = 90
Unlike tuples, dictionaries allow modification.
Adding New Key–Value Pairs
student["grade"] = "A"
Deleting Elements
del student["class"]
10.9 Dictionary Operations
Membership Check (Keys Only)
print("name" in student)
print("age" not in student)
Membership checks keys, not values.
Length of Dictionary
print(len(student))
Comparison
Dictionaries cannot be compared using <, >.
Only equality (==) checks are allowed.
10.10 Traversing a Dictionary
Traversing Keys
for key in student:
print(key)
Traversing Values
for value in student.values():
print(value)
Traversing Key–Value Pairs
for key, value in student.items():
print(key, ":", value)
This is the most common and useful traversal method.
10.11 Dictionary Methods and Built-in Functions
Common Dictionary Methods
print(student.keys())
print(student.values())
print(student.items())
get() Method (Safer Access)
print(student.get("marks"))
print(student.get("age", "Not Found"))
Prevents runtime errors.
pop() Method
student.pop("marks")
Removes and returns value.
update() Method
student.update({"marks": 88, "section": "A"})
Built-in Functions
print(len(student))
Functions like max() and min() operate on keys only.
10.12 Manipulating Dictionaries
Example 1: Counting Frequency of Elements
s = "programming"
freq = {}
for ch in s:
freq[ch] = freq.get(ch, 0) + 1
print(freq)
Example 2: Student Marks Processing
marks = {
"Math": 85,
"Science": 90,
"English": 78
}
total = 0
for m in marks.values():
total += m
print("Total:", total)
print("Average:", total / len(marks))
Example 3: Finding Highest Marks Subject
highest = ""
max_marks = 0
for subject, score in marks.items():
if score > max_marks:
max_marks = score
highest = subject
print("Highest:", highest)
Key Conceptual Takeaways
Tuple
Tuplesareimmutablesequences, i.e., we cannot change the elements of a tuple once it is created.- Elements of a tuple are put in
round bracketsseparated by commas. - If a
sequencehas comma separated elements without parentheses, it is also treated as a tuple. - Tuples are ordered sequences as each element has a fixed position.
- Indexing is used to access the elements of the tuple; two way indexing holds in dictionaries as in strings and lists.
- Operator
+adds one sequence (string, list, tuple) to the end of other. - Operator
*repeats a sequence (string, list, tuple) by specified number of times - Membership operator
intells if an element is present in the sequence or not andnot indoes the opposite. - Tuple manipulation functions are:
len(), tuple(), count(), index(), sorted(), min(), max(), sum().
Dictionary
Dictionaryis a mapping (non-scalar) data type. It is an unordered collection of key-value pair; key-value pair are put insidecurly braces.- Each
keyis separated from its value by acolon (:). - Keys are
uniqueand act as theindex. Keysare ofimmutabletype butvaluescan bemutable.