Python 3.12+ Core Data Structures Data Analytics Foundation

Python Collections: Lists, Tuples & Dictionaries

Master organizing and manipulating datasets: ordered mutable lists, immutable tuples, key-value dictionaries, indexing, operations (append, remove, del, len), and structured nested records.

Read Time: 22 mins
Primary Source: Official Python 3.12+ Documentation
Interactive Labs: 5 Live Coding Workbenches
1

1. Why Do We Need Collections?

Storing related values in separate variables is unmanageable when working with real datasets:

❌ Individual Variables (Unscalable)
name1 = "Amit"
name2 = "Priya"
name3 = "Rahul"
# Cannot easily loop, filter, or sort!
✅ Python Collections (Structured & Iterable)
names = ["Amit", "Priya", "Rahul"]
# Store, loop, slice, and mutate in 1 object!
The Big Three Python Collections:
1. List []: Ordered, mutable sequence of values.
2. Tuple (): Ordered, permanent (immutable) sequence.
3. Dictionary : Key-value mapping for labeled attributes.
2

2. Lists: Ordered & Mutable

A list is created using square brackets []. Python lists are 0-indexed:

Python 0-Based & Negative Indexing Map
Index: 0 (or -3)
"Amit"
Index: 1 (or -2)
"Priya"
Index: 2 (or -1)
"Rahul"
OperationPython CodeResult / Behavior
Access first itemnames[0]Returns "Amit"
Access last itemnames[-1]Returns "Rahul"
Modify elementnames[0] = "Sumit"Replaces first element (mutable)
Append new itemnames.append("Neha")Adds to the end of the list
Remove itemnames.remove("Priya")Deletes the specified value
Count elementslen(names)Returns total number of items
3

3. 🔥 Live Lab: List Manipulation

Practice list indexing, mutation, appending, and removal:

Exercise 1: Manipulate Sales List
List Lab
Requirements:
  • Print first value: print(sales[0])
  • Print last value: print(sales[-1])
  • Change first value to 50000: sales[0] = 50000
  • Append 60000: sales.append(60000)
  • Remove 32000: sales.remove(32000)
  • Print updated list and length: print(sales) and print(len(sales))
4

4. Lists + Loops: The Core Data Processing Unit

In data analytics, lists store multiple records, and loops process each record sequentially:

5

5. Tuples: Ordered & Immutable

A tuple is defined using parentheses (). Like lists, tuples are ordered and 0-indexed, but cannot be modified after creation:

coordinates = (19.07, 72.87)

print(coordinates[0])  # Accesses 19.07
print(len(coordinates))  # Returns 2
Why Immutability Matters:
Immutability protects sensitive data from accidental modification. When working with geographic coordinates, database configurations, or fixed dimensions, a tuple guarantees the values remain intact throughout program execution.
6

6. List vs Tuple: Head-to-Head Comparison

PropertyList []Tuple ()
MutabilityMutable (Can add, remove, change items)Immutable (Fixed after creation)
SyntaxSquare brackets: [1, 2, 3]Parentheses: (1, 2, 3)
When to ChooseWhen the data will grow, shrink, or be sortedWhen the data represents a fixed record or constant
ExamplesSales figures, customer names, transactionsGPS coordinates (lat, lon), RGB colors (255, 0, 0)
7

7. 🔥 Live Lab: Observing Tuple Immutability in Action

Run the code below to see the authentic TypeError Python raises when attempting to alter a tuple:

8

8. Dictionaries: Key-Value Mappings

A dictionary stores data in key: value pairs using curly braces {}:

student = {
    "name": "Amit",
    "age": 22,
    "marks": 85
}

print(student["name"])  # Access by key → "Amit"
Python 3.7+ Insertion-Order Guarantee:
Since Python 3.7, dictionaries are guaranteed by the language specification to preserve insertion order. Iterating over keys or values produces them in the exact order they were added.
9

9. 🔥 Live Lab: Dictionary Operations

Modify, insert, access, and delete key-value pairs in a dictionary:

Exercise: Update Student Dictionary
Dict Lab
Requirements:
  • Print student name: print(student["name"])
  • Change marks to 90: student["marks"] = 90
  • Add a new key "city": student["city"] = "Mumbai"
  • Delete "age": del student["age"]
  • Print the updated dictionary: print(student)
10

10. List vs Tuple vs Dictionary: The Master Matrix

StructureStoresOrdered?Mutable?Access Method
List []Multiple valuesYesYesNumeric Index: list[0]
Tuple ()Multiple valuesYesNoNumeric Index: tuple[0]
Dictionary {}Key-Value pairsYes (Python 3.7+)YesBy Key: dict["key"]
11

11. 🔥 Scenario Chooser: When to Use What?

1. A list of product prices that will change over time.
2. Fixed GPS coordinates (latitude, longitude) of a warehouse.
3. A single student record with named fields (name, age, grade).
4. Daily sales numbers recorded at the end of each day.
5. Fixed RGB color values (255, 128, 0).
12

12. Nested Data: Real-World Datasets

In real data analytics, data structures nest inside each other. A table of rows is represented as a list of dictionaries:

students = [
    {"name": "Amit", "marks": 85},
    {"name": "Priya", "marks": 92}
]
13

13. Practical Data Analytics: Records & Tables

Notice the standard architectural duality:

LIST []

Used to hold multiple records (e.g., 10,000 transactions).

DICTIONARY {}

Used to describe one record with named column fields (product, price, qty).

14

14. 🔥 Final Live Challenge: Student Analytics

Process a list of student records, extract dictionary fields, and identify high performers:

Capstone Challenge: Process Nested Records
Capstone
15

15. Common Beginner Mistakes Checklist

MistakeIncorrect CodeCorrect CodeWhy It Fails
1-based indexing assumptionfirst = names[1]first = names[0]Python sequence indexing starts strictly at 0.
Trying to modify a tupletuple[0] = 5Use a list insteadTuples are immutable; throws TypeError.
Using index on dictionarystudent[0]student["name"]Dictionaries are indexed by keys, not integer positions.
Misspelling dictionary keystudent["nam"]student["name"]Non-existent keys throw KeyError.
16

16. Comprehensive Knowledge Assessment

Test your mastery of Python lists, tuples, and dictionaries:

TEST YOUR KNOWLEDGE

Python Collections Mastery Quiz

Test your understanding of list mutability, tuple immutability, dictionary key-value access, and Python 3.7+ ordering guarantees.

Question 1 of 5Current Score: 0 / 0
Q1

1. What error does Python raise when you attempt to modify an element in a tuple (e.g., t = (10, 20); t[0] = 99)?