Getting Started with Python for Beginners #4: Collections & Data Structures

You’ve learned how to set up Python, write basic code, handle user input, and control the flow of your program. Now it’s time to explore how to store and manage larger amounts of data. In this post, we’ll dive into:

  • Working with lists, tuples, and dictionaries
  • Accessing, modifying, and iterating through these data structures
  • Applying these collections in a small project to manage and manipulate data more effectively

By the end of this lesson, you’ll have a solid foundation for organizing your data and making your programs more powerful.

Lists: Ordered Collections of Items

A list is one of the most common data structures in Python. It’s an ordered collection of items (which can be of different types). You create a list by placing items inside square brackets [], separated by commas:

fruits = ["apple", "banana", "cherry"]

Accessing Items:
You can access an item in a list using its index (starting at 0):

print(fruits[0])  # apple
print(fruits[1])  # banana

Modifying Lists:
Lists are mutable, which means you can change them after they’re created:

fruits[0] = "mango"  # Change "apple" to "mango"
print(fruits)         # ["mango", "banana", "cherry"]

Adding and Removing Items:

  • append() adds an item to the end.
  • insert() adds an item at a specific position.
  • remove() removes a specific item.
  • pop() removes an item at a given index (default is the last item).
fruits.append("orange")
fruits.insert(1, "grape")
print(fruits)  # ["mango", "grape", "banana", "cherry", "orange"]

fruits.remove("grape")
popped = fruits.pop()
print(popped)   # "orange"
print(fruits)   # ["mango", "banana", "cherry"]

For a deeper dive into lists, watch this intro to Python lists video.

Tuples: Immutable Collections

A tuple is like a list, but immutable—once created, you cannot change, add, or remove items. You create tuples with parentheses ():

colors = ("red", "green", "blue")

You can access tuple elements the same way as lists:

print(colors[0])  # red

However, you can’t modify a tuple:

# colors[0] = "yellow"  # This will cause an error because tuples are immutable

Tuples are great when you want to ensure that data cannot be changed. Learn more about tuples in this quick tutorial.

Dictionaries: Key-Value Pairs

A dictionary is a collection of key-value pairs. Instead of accessing items by an index like lists, you access them by their keys. Dictionaries are created with curly braces {}:

student = {
    "name": "Alice",
    "age": 25,
    "major": "Computer Science"
}

Accessing Values:

print(student["name"])  # Alice
print(student["age"])   # 25

Modifying Dictionaries:
You can add, change, or remove key-value pairs easily:

student["age"] = 26
student["grade"] = "A"
print(student)

del student["major"]
print(student)

Iterating Over Dictionaries:
You can loop through keys, values, or both:

for key in student:
    print(key, student[key])

Or use built-in methods:

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

Check out this dictionary introduction video for more examples.

Slicing and Iterating Through Collections

Slicing allows you to extract a portion of a list or tuple:

numbers = [10, 20, 30, 40, 50]
print(numbers[1:4])  # [20, 30, 40]
print(numbers[:3])   # [10, 20, 30]
print(numbers[2:])   # [30, 40, 50]

Iterating is straightforward with for loops:

for number in numbers:
    print(number)

This will print each element in the list. You can also iterate over dictionary keys or values as mentioned above.

For a quick look at slicing, watch this slicing tutorial.

Small Project: Managing a To-Do List

Let’s put these concepts into practice with a simple project—a to-do list manager.

todo_list = []

while True:
    print("\n--- To-Do List Manager ---")
    print("1. Add a task")
    print("2. View tasks")
    print("3. Remove a task")
    print("4. Quit")

    choice = input("Enter your choice: ")

    if choice == "1":
        task = input("Enter the new task: ")
        todo_list.append(task)
        print(f"Task '{task}' added.")
    elif choice == "2":
        print("\nYour tasks:")
        for idx, task in enumerate(todo_list, start=1):
            print(f"{idx}. {task}")
    elif choice == "3":
        task_num = int(input("Enter the task number to remove: "))
        if 1 <= task_num <= len(todo_list):
            removed = todo_list.pop(task_num - 1)
            print(f"Task '{removed}' removed.")
        else:
            print("Invalid task number.")
    elif choice == "4":
        print("Goodbye!")
        break
    else:
        print("Invalid choice. Please try again.")

This simple program demonstrates:

  • Using a list to store tasks
  • Adding, viewing, and removing tasks from the list
  • Using enumerate() to display tasks with their index

Experiment with this code, try adding new features (like editing tasks or sorting the list), and don’t hesitate to explore different data structures.

What’s Next?

You’ve now got a solid grounding in Python’s core data structures: lists, tuples, and dictionaries. With these tools, you can store, manipulate, and manage data effectively. Next, we’ll introduce functions—reusable blocks of code that help keep your projects organized and maintainable.

Coming Up: Getting Started with Python for Beginners #5: Functions – Reusable Blocks of Code

  • Defining and calling functions
  • Parameters, arguments, and return values
  • Applying functions to keep your code clean and efficient

If you’re curious, check out this introduction to Python functions to get a head start.

Wrapping Up

Collections and data structures are at the heart of almost every Python program. Mastering lists, tuples, and dictionaries gives you the power to build more complex and useful applications. Keep practicing, try out different data manipulations, and have fun exploring all the possibilities!

반응형