🎓 A1Learner
🔍
0 of 52 lessons completed

Python Choosing the Right Collection

Each collection fits a different job. The job picks the collection, not habit.

A list keeps order and repeats

The list keeps 88 twice, in place. append() adds 71 at the end.

scores = [88, 95, 88]
scores.append(71)
print(scores)
print(scores[0])

A dict finds by name

scores["bob"] gives 95 by name. A new key adds Cy with 71.

scores = {"ada": 88, "bob": 95}
print(scores["bob"])
scores["cy"] = 71
print(scores)

A set drops repeats

The set holds Ada and Bob once each. Its length is 2, not 3.

seen = {"ada", "bob", "ada"}
print(len(seen))
print("ada" in seen)
print("cy" in seen)

A tuple holds a fixed pair

The pair (3, 4) holds two numbers in place. Each number comes back by its place.

point = (3, 4)
print(point)
print(point[0])
print(point[1])

Example

names = ["ada", "bob", "ada", "cy"]
scores = {"ada": 88, "bob": 95, "cy": 71}
seen = set(names)
best = ("bob", 95)
print("Names:", names)
print("Count:", len(names))
print("Unique:", len(seen))
print("Bob:", scores["bob"])
print("Best:", best)

Key points

  • List: ordered items that may repeat, found by place
  • Use a list when order matters and repeats are allowed
  • Dict: items found by a name, called a key
  • Use a dict when each item needs finding by its name
  • Set: unordered items with no repeats, checked by membership
  • Use a set when repeats must vanish and only membership matters
  • Tuple: a fixed group of items, found by place
  • Use a tuple for a small fixed group, like a pair of numbers

In this example, four tools share one small job. The list holds the names in order, repeats and all. The set counts three unique names from that list. The dict finds the score for Bob by name. The tuple holds the best player and score as one fixed pair.

Note

A set has no order to rely on, while a list keeps the order items arrived in.

Try it Yourself

Edit the code, then press Run.

Running is simulated · Python Playground

Exercise

Which collection drops repeats and answers membership checks?