SAMANTUS Python for Data Analytics — Complete Training Manual MODULE 08
← Back to Course Index

Data Structures


On This Page

Module 8: Data Structures


8.1  Lists — Creation & CRUD Operations

A list is an ordered, changeable collection that can hold multiple items — even of different data types. Lists are the most commonly used data structure in Python.

► Creating a List
courses = ["SEO", "Google Ads", "Meta Ads", "AI Tools"]
print(courses)
print(type(courses))
print(len(courses))
Output
['SEO', 'Google Ads', 'Meta Ads', 'AI Tools']
<class 'list'>
4

CRUD Operations — Create, Read, Update, Delete

► CRUD on Lists
courses = ["SEO", "Google Ads", "Meta Ads"]

# CREATE (add)
courses.append("AI Tools")

# READ
print(courses[1])          # Google Ads

# UPDATE
courses[0] = "Advanced SEO"

# DELETE
courses.remove("Meta Ads")

print(courses)
Output
['Advanced SEO', 'Google Ads', 'AI Tools']

8.2  List Methods

MethodPurposeExample
append(x)Adds item to the endcourses.append("SEO")
insert(i, x)Inserts at a specific indexcourses.insert(0, "New")
remove(x)Removes first matching itemcourses.remove("SEO")
pop(i)Removes & returns item at indexcourses.pop(0)
sort()Sorts the list in placemarks.sort()
reverse()Reverses the list ordercourses.reverse()
index(x)Finds index of an itemcourses.index("SEO")
count(x)Counts occurrences of an itemmarks.count(90)
✗ Common Mistake
sort() sorts the list in place and returns None — writing courses = courses.sort() will make your list disappear! Just call courses.sort() on its own line.

8.3  Nested Lists

A nested list is a list that contains other lists — useful for representing tables or grids of data.

► Nested List Example
students = [
    ["Priya", 85],
    ["Rahul", 72],
    ["Anita", 91]
]

print(students[0])       # first student record
print(students[0][0])    # first student's name
print(students[2][1])    # third student's marks
Output
['Priya', 85]
Priya
91

8.4  Tuples

A tuple is like a list, but it is immutable — once created, its values cannot be changed. Tuples are used for data that should never be modified, like coordinates or fixed settings.

► Working with Tuples
course_info = ("SEO", 8, 12000)   # (name, weeks, fee)
print(course_info)
print(course_info[0])

# course_info[0] = "PPC"   # This would raise an ERROR - tuples are immutable
Output
('SEO', 8, 12000)
SEO
ℹ Why Use Tuples?
Use tuples when data must stay constant throughout the program — e.g. a course's fixed duration and fee, database records, or function return values that shouldn't be altered.

8.5  Sets

A set is an unordered collection of unique items — duplicates are automatically removed. Sets are excellent for removing duplicate data and comparing groups.

► Working with Sets
skills_raj = {"SEO", "Google Ads", "Content Writing"}
skills_meena = {"Google Ads", "Meta Ads", "Content Writing"}

print(skills_raj.union(skills_meena))          # all unique skills combined
print(skills_raj.intersection(skills_meena))   # common skills
print(skills_raj.difference(skills_meena))     # only Raj has these
Output
{'SEO', 'Google Ads', 'Content Writing', 'Meta Ads'}
{'Google Ads', 'Content Writing'}
{'SEO'}
✓ Real-World Use Case
Sets are perfect for removing duplicate rows from a raw dataset or finding common customers between two marketing campaign lists.

8.6  Dictionaries

A dictionary stores data as key-value pairs, allowing fast lookup by a meaningful key instead of a numeric index. This is one of the most important data structures for real data work.

► Working with Dictionaries
student = {
    "name": "Priya Sharma",
    "course": "Digital Marketing",
    "fee": 15000,
    "enrolled": True
}

print(student["name"])       # accessing by key
student["fee"] = 13500       # updating a value
student["batch"] = "Morning" # adding a new key
print(student)
Output
Priya Sharma
{'name': 'Priya Sharma', 'course': 'Digital Marketing', 'fee': 13500, 'enrolled': True, 'batch': 'Morning'}
MethodPurpose
keys()Returns all keys in the dictionary
values()Returns all values in the dictionary
items()Returns all key-value pairs
get(key)Safely retrieves a value (no error if missing)
update()Updates multiple key-value pairs at once
pop(key)Removes a key and returns its value

8.7  Comparison: List vs Tuple vs Set vs Dict

FeatureListTupleSetDict
Ordered?YesYesNoYes (3.7+)
Changeable?YesNoYesYes
Duplicates?AllowedAllowedNot allowedKeys unique
Syntax[ ]( ){ }{key: value}
Best ForGeneral sequencesFixed/constant dataUniqueness & set opsLabeled/structured data

8.8  Real-World Examples

► Real Example: Course Enrollment System
enrollments = [
    {"name": "Priya", "course": "SEO", "fee": 12000},
    {"name": "Rahul", "course": "Google Ads", "fee": 15000},
    {"name": "Anita", "course": "SEO", "fee": 12000},
]

total_revenue = sum(student["fee"] for student in enrollments)
print("Total Revenue:", total_revenue)

seo_students = [s["name"] for s in enrollments if s["course"] == "SEO"]
print("SEO Students:", seo_students)
Output
Total Revenue: 39000
SEO Students: ['Priya', 'Anita']
✓ Instructor Tip
This 'list of dictionaries' pattern is exactly how real business data looks — it's the perfect bridge before students learn Pandas DataFrames in Module 14.

8.9  Practical Exercises

Basic (5 Questions)

1. Create a list of 5 course names and print the 2nd and last item.

2. Create a tuple to store a course's name, duration, and fee.

3. Create a set of your 5 favorite skills and try adding a duplicate to see what happens.

4. Create a dictionary for one student with name, age, and course.

5. Add, update, and remove one item from a list of your choice.

Intermediate (5 Questions)

1. Create a nested list of 4 students with [name, marks] and print all names using a loop.

2. Use set operations to find common and different skills between 2 people.

3. Create a dictionary of 5 products with their prices, then print only the product names.

4. Write a program to sort a list of numbers in descending order using sort().

5. Use dictionary.get() to safely check for a key that may not exist, without causing an error.

Advanced (5 Questions)

1. Build a list of dictionaries representing 5 students (name, course, fee) and calculate total revenue.

2. From that same list, extract only the names of students enrolled in a specific course.

3. Remove duplicate entries from a list of customer emails using a set.

4. Build a simple 'Inventory System' using a dictionary where keys are product names and values are stock counts; write functions to add stock and sell stock.

5. Write a program to find the student with the highest marks from a nested list of [name, marks] pairs.

8.10  Module Quiz (MCQs)

Q1. Which data structure is immutable?

Q2. Which data structure does not allow duplicate values?

Q3. How do you access a dictionary value safely without an error?

Q4. Which method adds an item to the end of a list?

Q5. What symbol is used to create a dictionary?

ℹ Answer Key
1-b, 2-c, 3-b, 4-c, 5-d

8.11  Module Assignment

Assignment: Mini Student Management System

Expected Output: A working script demonstrating list, dictionary, and set operations together on realistic student enrollment data.

8.12  Interview Questions — Module 8


8.13  Student Notes Page

Use this space to write down key points, doubts, and your own examples from today's session.