Choosing the Right Collection

Collection Types

Choosing the Right Collection

In this tutorial, we'll pick the collection type that fits the job.

Python gives you several collection types because different problems need different shapes of data.

Use a List for Ordered Items

Use a list when order matters or when you want to add and remove items.

shopping_list = ["bread", "milk", "apples"]
shopping_list.append("rice")

Good for:

  • Tasks
  • Scores
  • Names in order
  • Items in a basket

Use a Dictionary for Labelled Data

Use a dictionary when each value needs a name.

user = {
    "username": "ada99",
    "email": "ada@example.com",
    "is_admin": False,
}

Good for:

  • User profiles
  • Products
  • Settings
  • Records from a database

Use a Set for Unique Values

Use a set when duplicates should disappear or membership checks are important.

tags = {"python", "web", "beginner"}

Good for:

  • Unique tags
  • Allowed usernames
  • Comparing groups

Use a Tuple for Fixed Groups

Use a tuple when the group should not change.

rgb = (255, 200, 120)
point = (5, 9)

Good for:

  • Coordinates
  • Pairs
  • Fixed settings

Quick Decision

Ask yourself:

  • Do I need labels? Use a dictionary.
  • Do I need order and changes? Use a list.
  • Do I need unique values? Use a set.
  • Do I need a fixed group? Use a tuple.

Practice

Choose a collection type for: a school register, a single student's details, unique club names, and a map coordinate.