Data Types Guide
Core Objectives: Learn to group and organize information using Python 3's built-in collections: Lists, Tuples, Sets, and Dictionaries. Understand how text strings act as sequences, choose the best collection type for different scenarios, and learn how Python accesses data quickly.
Python Data Types: Lists, Dictionaries & More
Up until now, you've stored one piece of information inside a single variable:
main.pyRunnablestudent_name = "Alex Johnson" student_grade = 95
But what if you need to manage a whole classroom roster of 30 students, or list all the test scores from a semester? Creating 30 different variables would be exhausting!
To solve this, Python provides four built-in Data Types that allow us to group multiple items together under a single name: Lists, Tuples, Sets, and Dictionaries.
1. Introduction to Collections
A Data Type is simply a container that holds multiple pieces of data. When learning how to use them, we look at two main features:
- Order: Are the items sorted in a specific line where we can point to the "first item" (index
0), "second item" (index1), etc.? - Mutability (Changeability): Can we add, remove, or swap items after we create the collection?
2. Lists: Your Flexible Shopping List
Definition: A List is an ordered, changeable collection of items enclosed in square brackets (
[]).
Think of a List like a shopping list written on a notepad. You can add new items to the bottom, cross items off, replace items, and even list the same item twice (like buying two cartons of milk).
Core Operations and Syntax
main.pyRunnable## Declare a list of course subjects courses = ["Physics", "Chemistry", "Algebra"] ## 1. Accessing items by their position (Zero-Indexed) ## Python starts counting positions at 0! print("First course:", courses[0]) # Outputs: Physics print("Last course:", courses[-1]) # Outputs: Algebra (Negative indices read from the end!) ## 2. Changing an item (Mutability) courses[2] = "Calculus" print("After update:", courses) # Outputs: ['Physics', 'Chemistry', 'Calculus'] ## 3. Adding elements courses.append("Biology") # Adds "Biology" to the very end courses.insert(1, "English Lit") # Inserts "English Lit" at index 1, pushing others back print("After expansion:", courses) # Outputs: ['Physics', 'English Lit', 'Chemistry', 'Calculus', 'Biology'] ## 4. Removing elements courses.remove("Chemistry") # Removes the first occurrence of "Chemistry" removed_item = courses.pop(2) # Removes and returns the item at position 2 ("Calculus") print("After removal:", courses) # Outputs: ['Physics', 'English Lit', 'Biology']
Slicing: Grabbing Sections of a List
You can extract a sub-section of a list using the range syntax [start:stop:step]. Note that the stop position is not included in the result!
main.pyRunnablegrades = [90, 85, 78, 92, 88, 95] ## Extract the first three elements (indices 0, 1, and 2) first_three = grades[:3] # Outputs: [90, 85, 78] ## Extract everything from index 3 to the end remaining = grades[3:] # Outputs: [92, 88, 95] ## Reverse the list using step size -1 reversed_grades = grades[::-1] # Outputs: [95, 88, 92, 78, 85, 90]
Self-Check Assessment
3. Tuples: The Locked Coordinates
Definition: A Tuple is an ordered, unchangeable collection of elements enclosed in parentheses (
()).
Think of a Tuple like a set of GPS coordinates (latitude and longitude) or your date of birth. Once recorded, you should never alter them.
Tuples are used when you want to protect your data from accidental changes or overrides.
Core Operations and Syntax
main.pyRunnable## Declare a student coordinate record geo_location = (37.7749, -122.4194) ## 1. Index-Based Access (Same as lists) print("Latitude:", geo_location[0]) ## 2. Trying to modify a tuple will cause an error! ## geo_location[0] = 34.0522 # ❌ TypeError: 'tuple' object does not support item assignment ## 3. Creating a Tuple with only one element ## Always add a trailing comma, otherwise Python thinks it's just a normal number in parentheses! failed_tuple = (2026) # Python sees this as the integer 2026 valid_tuple = (2026,) # Python sees this correctly as a Tuple! ## 4. Unpacking a Tuple ## Assign tuple elements directly to individual variables in a single line. student_record = ("Alice Vance", 16, "A") name, age, grade = student_record print(f"Student: {name} | Age: {age} | Grade: {grade}")
Self-Check Assessment
4. Sets: The Bag of Unique Stickers
Definition: A Set is an unordered collection of unique elements enclosed in curly braces (
{}).
Imagine you have a bag of collectible stickers. You only care about having unique stickers; you don't care about their order inside the bag, and you definitely don't want duplicates of the same sticker. If you try to add a duplicate, it is ignored.
Core Operations and Syntax
main.pyRunnable## Declare a set of registered students (note duplicate "Bob") registered_students = {"Alice", "Bob", "Charlie", "Bob"} print("Unique Registrants:", registered_students) # Outputs: {'Alice', 'Bob', 'Charlie'} (Duplicates are filtered!) ## 1. Adding and removing elements registered_students.add("David") registered_students.discard("Bob") # Safely removes Bob without crashing if Bob is already gone print("Updated Set:", registered_students) ## 2. Instantly checking if an item exists ## Checking if an item is in a set is extremely fast! is_enrolled = "Alice" in registered_students print("Is Alice registered?", is_enrolled)
Mathematical Set Comparisons
Sets allow you to compare collections using standard math logic:
main.pyRunnablechess_club = {"Alice", "Bob", "Charlie"} drama_club = {"Charlie", "David", "Emma"} ## 1. Intersection: Who is in BOTH clubs? both_clubs = chess_club.intersection(drama_club) # Or: chess_club & drama_club print("In Both Clubs:", both_clubs) # Outputs: {'Charlie'} ## 2. Union: Who is participating in AT LEAST ONE club? any_club = chess_club.union(drama_club) # Or: chess_club | drama_club print("All Unique Members:", any_club) # Outputs: {'Alice', 'Bob', 'Charlie', 'David', 'Emma'} ## 3. Difference: Who is in Chess but NOT Drama? chess_only = chess_club.difference(drama_club) # Or: chess_club - drama_club print("Chess Only:", chess_only) # Outputs: {'Alice', 'Bob'}
Self-Check Assessment
5. Dictionaries: Your Phone's Contacts Book
Definition: A Dictionary is an unordered, changeable collection of key-value pairs enclosed in curly braces (
{}).
Think of a dictionary like your phone's contacts book. You search for a unique name (the Key), and it points directly to their phone number or details (the Value).
Core Operations and Syntax
main.pyRunnable## Declare a dictionary storing student grades grades_database = { "Alice": 95, "Bob": 87, "Charlie": 92 } ## 1. Looking up a value using its key label print("Alice's Grade:", grades_database["Alice"]) ## 2. Safe lookups to prevent crashes ## If you search for a missing key using grades_database["David"], Python will crash! ## Use .get() to return a safe fallback value instead of crashing. david_grade = grades_database.get("David", 0) print("David's Grade (Safe Check):", david_grade) # Outputs: 0 (since David is missing) ## 3. Modifying and adding entries grades_database["Bob"] = 90 # Updates Bob's existing grade grades_database["David"] = 88 # Adds a brand new contact/entry! print("Updated Database:", grades_database) ## 4. Removing entries removed_grade = grades_database.pop("Charlie") # Removes Charlie and returns his score print("Grades after pop:", grades_database)
Extracting Keys and Values
main.pyRunnableinventory = {"Laptop": 12, "Monitor": 8, "Keyboard": 15} ## Extract all product names (Keys) print("Products:", list(inventory.keys())) ## Extract all stock numbers (Values) print("Stock Counts:", list(inventory.values()))
Self-Check Assessment
6. Strings: Text as a Chain of Letters
In Python, a string is a piece of text (like "Pynex"). But Python actually treats a string as a sequence or "chain" of individual character letters! This means we can access letters using their index positions just like we do in Lists.
main.pyRunnableschool_name = "Pynex" ## Index-based character retrieval print("First character:", school_name[0]) # Outputs: P print("Last character:", school_name[-1]) # Outputs: x ## Sub-string slicing sub_string = school_name[1:4] print("Slice [1:4]:", sub_string) # Outputs: yne
7. Real-World Scenarios
Here is how these structures are combined to solve realistic problems.
Scenario 1: Daily Course and Schedule Management
- List: Tracks the chronologically ordered periods.
- Tuple: Keeps the student demographic constant.
- Set: Tracks unique subject areas studied.
main.pyRunnable## Student profile remains fixed student_profile = ("Marcus Vance", "10th Grade") ## Schedule sequence is ordered and can change schedule = ["Algebra II", "English Lit", "US History", "Chemistry"] schedule.append("Computer Science") # Student adds an elective class ## Extract all unique departments represented (ignoring grade levels) departments = {"Mathematics", "Humanities", "Humanities", "Science", "Mathematics"} print("Unique academic departments represented:", departments)
Scenario 2: Student Gradebook and Attendance Database
- Dictionary: Maps student IDs to their academic records.
- Nested Dictionary: Stores multidimensional metrics per student.
main.pyRunnable## Store complex academic profiles inside a dictionary index gradebook = { "S001": { "name": "Alice Vance", "attendance": 95.5, "grades": [92, 88, 95] }, "S002": { "name": "Bob Smith", "attendance": 98.0, "grades": [85, 90, 87] } } ## Access Bob's attendance rate directly bob_attendance = gradebook["S002"]["attendance"] print(f"Bob Smith Attendance Rate: {bob_attendance}%") ## Retrieve Bob's first grade entry bob_first_grade = gradebook["S002"]["grades"][0] print(f"Bob Smith First Quiz Grade: {bob_first_grade}%")
8. Core Operations Reference Table
Here is a quick reference guide for the most important operations across all Data Types: Add, Delete, Insert, Update, Intersection, Union, and Difference.
List Operations
- Add:
my_list.append(item)adds to the end. - Insert:
my_list.insert(index, item)adds at a specific position. - Update:
my_list[index] = new_valuechanges an existing item. - Delete:
my_list.remove(item)deletes the first match, ormy_list.pop(index)removes by position.
Dictionary Operations
- Add / Update:
my_dict[key] = value(Adds if key is new, Updates if key exists). - Update (Multiple):
my_dict.update({'new_key': 'value'})merges another dictionary. - Delete:
my_dict.pop(key)removes the key-value pair.
Set Operations (Math & Mutations)
- Add:
my_set.add(item)adds a single unique item. - Delete:
my_set.discard(item)safely removes an item without crashing if it doesn't exist. - Intersection:
set_a.intersection(set_b)returns items that exist in both sets. - Union:
set_a.union(set_b)returns a combined set of all unique items from both sets. - Difference:
set_a.difference(set_b)returns items that exist inset_abut not inset_b.
9. Decision Matrix: Which One Do I Use?
Select your collection type based on your program's specific data requirements:
| Collection | Changeable (Mutable)? | Ordered? | Allows Duplicates? | Best Use Case |
|---|---|---|---|---|
List ([]) | Yes | Yes | Yes | Standard collections that need updates, sorting, and positioning. |
Tuple (()) | No | Yes | Yes | Constant records (like GPS coords or configurations) that shouldn't change. |
Set ({}) | Yes | No | No | Deduplicating values and checking membership instantly. |
Dictionary ({}) | Yes | No | No Keys | Phonebooks, rosters, or indexes where you lookup values by name. |
10. Performance & Speed: When to Use Which?
How do computers look up information inside these collections? Imagine you are looking for a card in a stack of cards.
- Linear Search ( - scanning one by one): If the cards are randomly stacked in a List, you have to scan them one by one from the top until you find it. If you have 1,000,000 cards, it might take 1,000,000 steps!
- Constant Lookup ( - instant access): If you use a Dictionary (using the card's name as a Key) or a Set, Python uses a mathematical shortcut to jump directly to the card. It takes 1 step, whether you have 10 cards or 10,000,000 cards!
Here is a quick reference table of operation speeds:
| Operation | List | Tuple | Set | Dictionary |
|---|---|---|---|---|
| Access by Position | Instant | Instant | N/A (Unordered) | N/A (Unordered) |
| Lookup by Key | N/A | N/A | N/A | Instant |
Search / Membership (in) | Slow (Scans all) | Slow (Scans all) | Instant | Instant (on Keys) |
| Insert / Delete at End | Instant | N/A | Instant | Instant |
💡 Core Rule: If your script needs to repeatedly check if an item is present inside a database of 100,000 items, convert your collection to a Set first. Checking membership using
item in listis slow, whileitem in setis instant.
11. Capstone Project: Invoice & Expenses Tracker
Now that you've learned about Python's data collections, it's time to apply them to a real-world Invoice and Expenses Tracker.
Imagine you are running a freelance business. You need a system that tracks:
- Your current active clients (Set for unique client names).
- The fixed tax brackets for different service types (Tuple since they rarely change).
- A ledger of all recent business expenses (List of numbers).
- Generated invoices mapping client names to their final bill (Dictionary).
Capstone Challenge:
Open the Python Compiler and try building this tracker:
- Create a
clientsSet storing 3 unique client names. - Create a
tax_ratesTuple containing standard rates:(0.05, 0.08, 0.12). - Create an
expensesList containing values like[120.50, 45.00, 300.00]. - Calculate the total expenses using Python's
sum(expenses). - Create an
invoicesDictionary mapping each client to a base bill amount, applying one of the tax rates to calculate the final total. print()the finalinvoicesdictionary!
12. Congratulations!
You have completed the Step 1: Python Data Types Guide. You've mastered Lists, Tuples, Sets, and Dictionaries!
Advance to the structured practice exercises to refine your capabilities!
Finished this lesson?
Mark it complete to advance your curriculum progress.