Python Full Tutorial — Part 6: Data Structures

By Suraj Ahir December 21, 2025 6 min read

Python — Python File I/O
Python — Python File I/O
← Part 5 Python Tutorial · Part 6 of 12 Part 7 →

Single variables store one value. Real programs work with collections — hundreds or thousands of values at once. Python gives you four powerful built-in data structures. Understanding when and how to use each one is a core skill.

1. List — Ordered, Mutable Collection

Lists store items in order and can be changed after creation:

List Operations
students = ["Amit", "Sara", "Raj", "Priya"]

print(students[0])      # Amit (first item)
print(students[-1])     # Priya (last item)
print(students[1:3])    # ['Sara', 'Raj'] (slicing)

students.append("Kiran")   # Add to end
students.insert(1, "Neha") # Insert at position 1
students.remove("Raj")     # Remove by value
popped = students.pop()    # Remove and return last item

print(len(students))    # Number of items
students.sort()         # Sort alphabetically
students.reverse()      # Reverse order

2. Tuple — Ordered, Immutable Collection

Tuples are like lists but cannot be changed after creation. Use them for data that should not change:

Tuple Examples
coordinates = (28.6139, 77.2090)  # Delhi lat/long
rgb_red = (255, 0, 0)
days = ("Mon", "Tue", "Wed", "Thu", "Fri")

lat, lng = coordinates  # Tuple unpacking
print(lat, lng)

3. Set — Unordered, No Duplicates

Sets automatically remove duplicates and support mathematical set operations:

Set Operations
skills_a = {"Python", "Linux", "Docker"}
skills_b = {"Docker", "Kubernetes", "AWS"}

print(skills_a | skills_b)   # Union — all unique skills
print(skills_a & skills_b)   # Intersection — common skills
print(skills_a - skills_b)   # Difference — only in A

# Remove duplicates from a list
names = ["Amit", "Sara", "Amit", "Raj", "Sara"]
unique_names = list(set(names))
print(unique_names)

4. Dictionary — Key-Value Pairs

Dictionaries store data as key-value pairs. They are incredibly useful for representing real-world objects:

Dictionary Operations
student = {
    "name": "Suraj Ahir",
    "age": 22,
    "city": "Rajkot",
    "skills": ["Python", "Linux", "Docker"]
}

print(student["name"])          # Access by key
print(student.get("email", "Not found"))  # Safe access

student["email"] = "suraj@example.com"  # Add key
student["age"] = 23                      # Update value
del student["city"]                      # Delete key

for key, value in student.items():
    print(f"{key}: {value}")

Choosing the Right Data Structure

In Part 7, we build functions — the tool that lets you write code once and use it everywhere.

Common Mistakes Beginners Make

Learning from common pitfalls saves hours of frustration. Here are the mistakes most beginners make in this area and how to avoid them.

The first mistake is trying to memorize syntax before understanding logic. Python syntax is simple — you could memorize it in a day. But if you do not understand why you are writing what you are writing, you will not be able to adapt when things change or when a problem looks slightly different. Always ask: what problem does this solve?

The second mistake is writing very long functions or very long scripts without breaking them into logical units. Real professional code is made of small, focused pieces that each do one thing well. The moment your code does two or three unrelated things in one block, it is time to split it up.

The third mistake is not reading error messages. Python's error messages are actually quite good. They tell you the file, the line number, the type of error, and often a description. Read the entire error before searching online. The answer is usually right there.

How This Topic Appears in Real Projects

In real codebases, every concept from this tutorial series appears constantly. Backend web applications built with Flask or Django use functions, classes, data structures, and error handling throughout every route and service. Data pipelines use loops and comprehensions to process thousands of records efficiently. CLI tools use argument parsing, file handling, and process management. DevOps automation scripts combine shell integration with Python logic to orchestrate deployments, monitor systems, and handle alerts.

The concepts that feel abstract right now will click into place the moment you start building something real. That is why the best way to learn is to pick a small project that solves a problem you actually have — even something simple like a personal expense tracker or a file organizer — and build it using everything you have learned so far.

Practice Exercise

Before moving to the next part, write a small program that uses what you learned in this section. Do not copy from anywhere. Start with a blank file and build it from memory. The struggle is the learning. If you get stuck, read the code examples again — do not just copy them. Understand each line, then close the examples and write the program yourself. This is how programming actually sticks.

Choosing the Right Data Structure

The choice of data structure is one of the most consequential decisions in writing efficient code. Use a list when you need an ordered, indexable collection where duplicates are allowed and the order of insertion matters. Use a dictionary when you need to look up values by a meaningful key rather than a numeric index — this is far more efficient than searching through a list. Use a set when you need to check membership, eliminate duplicates, or perform set operations like union or intersection. Use a tuple for fixed, immutable sequences — function return values, database records, or any collection that should not change after creation.

Dictionary Comprehensions and Advanced Usage

Just as list comprehensions provide concise list creation, dictionary comprehensions provide concise dictionary creation:

Dictionary Comprehension
names = ["Alice", "Bob", "Charlie"]
scores = [88, 95, 72]

# Create dict mapping name -> score
grade_book = {name: score for name, score in zip(names, scores)}
# Result: {"Alice": 88, "Bob": 95, "Charlie": 72}

# Filter: only those who passed
passing = {name: score for name, score in grade_book.items() if score >= 80}
# Result: {"Alice": 88, "Bob": 95}

# Square numbers mapped to their labels
square_map = {n: n**2 for n in range(1, 6)}
# Result: {1: 1, 2: 4, 3: 9, 4: 16, 5: 25}

Practice Exercise

Create a contact book program using a dictionary. Allow the user to add contacts (name as key, phone number as value), look up a contact by name, and list all contacts. Store the contacts in a dictionary and use dictionary methods like .get() for safe lookup, .items() for iteration, and check membership using the in operator to avoid duplicate entries.

Disclaimer: This content is for educational purposes only. SRJahir Tech does not guarantee any specific outcome, job placement, or exam result. Learning requires consistent effort and practical application.