Python Programming
Data Structures & Pandas DataFrames
Task 1: List • Tuple • Dictionary • Set Task 2: Student • Inventory • Employee DataFrames
Python Data Structures & DataFrames | Page 1
Task 1: Python Data Structures
Python has four core built-in data structures: List, Tuple, Dictionary, and Set. Below is one meaningful
example for each, demonstrating real-world usage.
1. List
A list is an ordered, mutable (changeable) collection that allows duplicate elements. It is defined using
square brackets [ ].
Key Characteristics
Ordered — elements maintain insertion order.
Mutable — you can add, remove, or change elements.
Allows duplicates — the same value can appear multiple times.
Indexed — elements are accessed by their position (0-based).
Example — Student Marks Manager
# List: manage a student's marks for 5 subjects
marks = [85, 92, 78, 90, 88]
print('Original marks:', marks)
# Add a new subject mark
[Link](95)
print('After adding new mark:', marks)
# Update the first mark
marks[0] = 87
print('After update:', marks)
# Remove the lowest mark
[Link](min(marks))
print('After removing lowest:', marks)
# Calculate average
average = sum(marks) / len(marks)
print(f'Average marks: {average:.2f}')
# Sort in descending order
[Link](reverse=True)
print('Sorted marks (high to low):', marks)
Output:
Original marks: [85, 92, 78, 90, 88]
After adding new mark: [85, 92, 78, 90, 88, 95]
After update: [87, 92, 78, 90, 88, 95]
After removing lowest: [87, 92, 90, 88, 95]
Average marks: 90.40
Sorted marks (high to low): [95, 92, 90, 88, 87]
Python Data Structures & DataFrames | Page 2
2. Tuple
A tuple is an ordered, immutable (unchangeable) collection. Once created, its elements cannot be
modified. It is defined using parentheses ( ).
Key Characteristics
Ordered — elements have a fixed position.
Immutable — cannot be changed after creation, making it safe for constant data.
Allows duplicates — can store repeated values.
Faster than lists — preferred for fixed data like coordinates, RGB colors, or records.
Example — GPS Location Record
# Tuple: store immutable GPS coordinates for city landmarks
eiffel_tower = ('Eiffel Tower', 48.8584, 2.2945, 'Paris')
statue_of_liberty = ('Statue of Liberty', 40.6892, -74.0445, 'New York')
taj_mahal = ('Taj Mahal', 27.1751, 78.0421, 'Agra')
landmarks = [eiffel_tower, statue_of_liberty, taj_mahal]
print('Landmark GPS Records:')
print('-' * 45)
for landmark in landmarks:
name, lat, lon, city = landmark # unpacking
print(f'{name} ({city})')
print(f' Lat: {lat}, Lon: {lon}')
# Tuples are immutable - this would raise an error:
# eiffel_tower[1] = 0 --> TypeError
print(f'Total landmarks tracked: {len(landmarks)}')
Output:
Landmark GPS Records:
---------------------------------------------
Eiffel Tower (Paris)
Lat: 48.8584, Lon: 2.2945
Statue of Liberty (New York)
Lat: 40.6892, Lon: -74.0445
Taj Mahal (Agra)
Lat: 27.1751, Lon: 78.0421
Total landmarks tracked: 3
3. Dictionary
A dictionary is an unordered collection of key-value pairs. Each key is unique and maps to a value. It is
defined using curly braces { key: value }.
Key Characteristics
Key-value pairs — data is stored and accessed via descriptive keys.
Mutable — keys and values can be added, updated, or deleted.
Keys must be unique — duplicate keys overwrite earlier values.
Fast lookup — retrieving a value by key is very efficient (O(1) average).
Example — Student Profile System
Python Data Structures & DataFrames | Page 3
# Dictionary: student profile with key-value data
student = {
'name': 'Alice',
'age': 20,
'department': 'Computer Science',
'marks': {'Math': 92, 'Python': 88, 'DSA': 95},
'active': True
}
# Access values
print(f"Name: {student['name']}")
print(f"Department: {student['department']}")
# Add a new key
student['email'] = 'alice@[Link]'
print(f"Email: {student['email']}")
# Update an existing value
student['age'] = 21
print(f"Updated Age: {student['age']}")
# Iterate over marks
print('Subject Marks:')
for subject, score in student['marks'].items():
print(f' {subject}: {score}')
# Check key existence
if 'email' in student:
print('Email is registered')
Output:
Name: Alice
Department: Computer Science
Email: alice@[Link]
Updated Age: 21
Subject Marks:
Math: 92
Python: 88
DSA: 95
Email is registered
4. Set
A set is an unordered collection of unique elements. Duplicate values are automatically removed. It is
defined using curly braces { } or the set() constructor.
Key Characteristics
Unordered — no guaranteed order of elements.
No duplicates — automatically eliminates repeated values.
Mutable — elements can be added or removed (but elements themselves must be immutable).
Supports set operations — union, intersection, difference, and symmetric difference.
Example — Common Course Enrollment Finder
# Set: find common courses between two students
alice_courses = {'Math', 'Python', 'DSA', 'DBMS', 'OS'}
bob_courses = {'Python', 'Networks', 'DSA', 'AI', 'OS'}
Python Data Structures & DataFrames | Page 4
print('Alice courses:', alice_courses)
print('Bob courses :', bob_courses)
# Intersection: courses both take
common = alice_courses & bob_courses
print('Common courses:', common)
# Union: all unique courses between both
all_courses = alice_courses | bob_courses
print('All courses:', all_courses)
# Difference: courses only Alice takes
only_alice = alice_courses - bob_courses
print('Only Alice:', only_alice)
# Add a new course to Alice's set
alice_courses.add('AI')
print('Alice after adding AI:', alice_courses)
# Duplicate is ignored automatically
alice_courses.add('Math')
print('After adding duplicate Math:', alice_courses)
Output:
Alice courses: {'Math', 'Python', 'DSA', 'DBMS', 'OS'}
Bob courses : {'Python', 'Networks', 'DSA', 'AI', 'OS'}
Common courses: {'Python', 'DSA', 'OS'}
All courses: {'Math', 'Python', 'DSA', 'DBMS', 'OS', 'Networks', 'AI'}
Only Alice: {'Math', 'DBMS'}
Alice after adding AI: {'Math', 'Python', 'DSA', 'DBMS', 'OS', 'AI'}
After adding duplicate Math: {'Math', 'Python', 'DSA', 'DBMS', 'OS', 'AI'}
Quick Comparison: All 4 Data Structures
Best Used
Structure Ordered Mutable Duplicates Syntax
For
List Yes Yes Yes [] Sequences,
collections
Tuple Yes No Yes () Fixed/
constant data
Dictionary Yes* Yes Keys: No { k:v } Key-value
mappings
Set No Yes No {} Unique items,
set ops
* Dictionaries maintain insertion order from Python 3.7+
Python Data Structures & DataFrames | Page 5
Task 2: Create DataFrames Using Dictionaries
A Pandas DataFrame is a two-dimensional, tabular data structure with labeled rows and columns —
similar to a spreadsheet. The most common way to create one is from a Python dictionary, where keys
become column names and values become column data.
DataFrame 1 — Student Records
This DataFrame stores student academic information including names, marks, grades, and pass/fail
status.
Code
import pandas as pd
# Dictionary representing student records
student_data = {
'Name': ['Alice', 'Bob', 'Charlie', 'Diana', 'Ethan'],
'Roll No': [101, 102, 103, 104, 105],
'Math': [92, 45, 78, 88, 55],
'Science': [85, 60, 70, 91, 48],
'English': [88, 72, 65, 95, 62],
'Percentage': [88.3, 59.0, 71.0, 91.3, 55.0],
'Grade': ['A', 'C', 'B', 'A+', 'D'],
'Result': ['Pass', 'Pass', 'Pass', 'Pass', 'Fail']
}
df_students = [Link](student_data)
print(df_students)
# Useful operations
print('\nAverage Percentage:', df_students['Percentage'].mean())
print('Top Scorer:', df_students.loc[df_students['Percentage'].idxmax(),
'Name'])
print('Passed Students:', df_students[df_students['Result'] == 'Pass']
['Name'].tolist())
DataFrame Output
Percenta
Name Roll No Math Science English Grade Result
ge
Alice 101 92 85 88 88.3 A Pass
Bob 102 45 60 72 59.0 C Pass
Charlie 103 78 70 65 71.0 B Pass
Diana 104 88 91 95 91.3 A+ Pass
Ethan 105 55 48 62 55.0 D Fail
Output:
Average Percentage: 72.92
Top Scorer: Diana
Python Data Structures & DataFrames | Page 6
Passed Students: ['Alice', 'Bob', 'Charlie', 'Diana']
DataFrame 2 — Product Inventory
This DataFrame represents a retail inventory system tracking products, their categories, pricing, stock
levels, and reorder status.
Code
import pandas as pd
# Dictionary representing product inventory
inventory_data = {
'Product': ['Laptop', 'Mouse', 'Keyboard', 'Monitor', 'Headphones',
'Webcam'],
'Category': ['Electronics', 'Accessories', 'Accessories', 'Electronics',
'Accessories', 'Electronics'],
'Price (INR)': [75000, 850, 1500, 18000, 3500, 4200],
'Stock': [12, 150, 80, 25, 60, 35],
'Sold': [8, 200, 120, 10, 45, 20],
'Reorder': [False, True, True, False, False, False]
}
df_inventory = [Link](inventory_data)
print(df_inventory)
# Operations
total_value = (df_inventory['Price (INR)'] * df_inventory['Stock']).sum()
print(f'\nTotal Inventory Value: Rs. {total_value:,}')
print('\nItems needing reorder:')
print(df_inventory[df_inventory['Reorder'] == True][['Product', 'Stock']])
DataFrame Output
Product Category Price (INR) Stock Sold Reorder
Laptop Electronics 75,000 12 8 False
Mouse Accessories 850 150 200 True
Keyboard Accessories 1,500 80 120 True
Monitor Electronics 18,000 25 10 False
Headphones Accessories 3,500 60 45 False
Webcam Electronics 4,200 35 20 False
Output:
Total Inventory Value: Rs. 28,22,000
Items needing reorder:
Product Stock
1 Mouse 150
2 Keyboard 80
Python Data Structures & DataFrames | Page 7
DataFrame 3 — Employee HR Records
This DataFrame models an HR system storing employee details such as department, salary, years of
experience, and performance rating.
Code
import pandas as pd
# Dictionary representing employee HR data
employee_data = {
'Emp ID': ['E001', 'E002', 'E003', 'E004', 'E005', 'E006'],
'Name': ['Ravi', 'Priya', 'Sam', 'Meena', 'John', 'Anita'],
'Department': ['IT', 'HR', 'Finance', 'IT', 'Marketing', 'Finance'],
'Salary': [65000, 48000, 55000, 72000, 43000, 58000],
'Experience': [5, 3, 7, 8, 2, 6],
'Rating': [4.5, 3.8, 4.2, 4.9, 3.5, 4.0],
'Status': ['Active', 'Active', 'Active', 'Active', 'Active', 'Active']
}
df_employees = [Link](employee_data)
print(df_employees)
# Operations
print(f'\nAverage Salary: Rs. {df_employees["Salary"].mean():,.0f}')
print(f'Highest Rated: {df_employees.loc[df_employees["Rating"].idxmax(),
"Name"]}')
dept_avg = df_employees.groupby('Department')['Salary'].mean()
print('\nAverage Salary by Department:')
print(dept_avg)
DataFrame Output
Departmen
Emp ID Name Salary Experience Rating Status
t
E001 Ravi IT 65,000 5 4.5 Active
E002 Priya HR 48,000 3 3.8 Active
E003 Sam Finance 55,000 7 4.2 Active
E004 Meena IT 72,000 8 4.9 Active
E005 John Marketing 43,000 2 3.5 Active
E006 Anita Finance 58,000 6 4.0 Active
Output:
Average Salary: Rs. 56,833
Highest Rated: Meena
Average Salary by Department:
Department
Finance 56500.0
HR 48000.0
IT 68500.0
Marketing 43000.0
Python Data Structures & DataFrames | Page 8
How Dictionary Becomes a DataFrame
# General pattern:
data = {
'Column1': [val1, val2, val3], # Each key = one column
'Column2': [val1, val2, val3], # All lists must be same length
}
df = [Link](data)
# Each list in the dictionary becomes a column
# The index (row numbers) is auto-assigned: 0, 1, 2 ...
# Use [Link](data, index=['a','b','c']) for custom row labels
Python Data Structures & DataFrames | Page 9