livepython.net
CHAPTER 14Tuples and Sets
14.4  WHICH ONE?

List vs Tuple vs Set vs Dictionary in Python

List vs Tuple vs Set vs Dictionary

A collection is one value that holds many values. Python has four of them: the list, the tuple, the set and the dictionary. Each one is best at a different job.

Think of a school. The lunch queue is a list: it has an order, and people join and leave. A student's date of birth is a tuple: fixed values that never change. The clubs a student has joined are a set: each club once, in no special order. The register from roll number to name is a dictionary: you look a name up by its number.

The four side by side

ListTupleSetDictionary
Written as[1, 2](1, 2){1, 2}{"a": 1}
Keeps the orderyesyesnoyes
Can changeyesnoyesyes
Duplicatesallowedalloweddroppedkeys: never
Read one itemby index: x[0]by index: x[0]no, ask with inby key: x["a"]
Empty[]()set(){}
Chapter9141413
PYTHONedit me
queue = ["Sunny", "Rocky", "Sunny"]
birthday = (12, 5, 2001)
clubs = {"chess", "music", "chess"}
ages = {"Sunny": 25, "Rocky": 23}
print(len(queue), len(birthday), len(clubs), len(ages))
OUTPUT
3 3 2 2

The list kept both Sunnys, the set dropped the second "chess", and the dictionary counts its keys.

What they share

  • len() works on all four.
  • in works on all four. On a dictionary, it checks the keys.
  • A for loop works on all four. On a dictionary, it goes through the keys; on a set, in the set's own order.

Common beginner doubt

"Which one is the best?" None of them! The list is the everyday choice, and you'll use it most. The other three are for special jobs: a tuple when the values must stay fixed, a set when every item must be unique, and a dictionary when you look things up by a name. The next lesson turns this into four quick questions.

List: ordered and changeable. Tuple: ordered and fixed. Set: unique, no order. Dictionary: values found by key.

your turnPick the right idea

Which collection drops repeated items all by itself?

Think about it, then pick one.
your turnPredict the output

What will this print?

x = ("a", "b", "a") print(len(x))
Your turn! What will this code show on the screen?

How to Choose the Right Python Collection

To choose a collection, ask what your data is like and what you'll do with it. Four questions, in this order, are enough.

Think of it like picking a container in the kitchen: a labelled jar, an egg tray, a spice rack. They all hold things, but one fits the job best.

The four questions

  1. Do you look values up by a name or a label? Use a dictionary.
  2. Must every item be unique, or do you mostly ask "is x in it?" Use a set.
  3. Is it a small, fixed group of values that belong together? Use a tuple.
  4. None of these? An ordered group that grows or changes: use a list.

Examples

The dataPickWhy
items in a shopping cartlistin order, you add and remove, repeats are fine
a point on a map, (x, y)tupletwo fixed values that belong together
usernames already takenseteach name once, and you ask "is it taken?"
a phone bookdictionarylook up a number by a name
the days of the weektuplethey never change
marks in the order they were handed inlistthe order matters, and two marks can be equal
words you've seen so farsetyou only care whether a word was seen

A set for "is it taken?"

Checking a name against taken usernames is a set's favourite job:

PYTHONedit me
taken = {"sunny", "rocky", "lucky"}
name = input()
if name.lower() in taken:
    print("Taken")
else:
    print("Available")
OUTPUT
Taken

lower() from chapter 12 makes Rocky match rocky. The set never needs an order, and a username can't be in it twice.

Common beginner doubt

"Can't I use a list for everything?" Often, yes: it would work. But a list keeps repeats you didn't want, can be changed by mistake, and in on a list checks the items one by one. The right collection makes your program say what you mean, and stops some bugs before they happen.

Look up by name: dictionary. Unique: set. Fixed: tuple. Everything else: list.

your turnPick the right idea

You store the x and y of a point that never moves. Which collection fits best?

Think about it, then pick one.
your turnPredict the output

Remember dictionaries from chapter 13?

ages = {"Sunny": 25, "Rocky": 23} print(ages["Rocky"])
Your turn! What will this code show on the screen?

Convert Between List, Tuple and Set

You can convert one collection into another with list(), tuple() and set(). Each one makes a new collection with the same items; the old one stays as it is.

PYTHONedit me
days = ("Mon", "Tue")
changeable = list(days)
changeable.append("Wed")
days = tuple(changeable)
print(days)
OUTPUT
('Mon', 'Tue', 'Wed')

That's the way to "change" a tuple: copy it into a list, change the list, and turn it back into a tuple.

Think of it like pouring water from a bottle into a glass: the same water, in a different container. And set() is a glass with a strainer: the repeats stay behind.

The converters

You writeYou get
list(x)a list with the items of x
tuple(x)a tuple with the items of x
set(x)a set: duplicates dropped, order lost
sorted(x)a sorted list, from any collection
list("abc")['a', 'b', 'c']: a string is a collection of characters too

A string into a set

Because a string is a collection of characters, set() finds the different letters in a word:

PYTHONedit me
letters = set("banana")
print(len(letters))
print(sorted(letters))
OUTPUT
3
['a', 'b', 'n']

From a set to a sorted tuple

sorted() always gives a list. Wrap it in tuple() if you want the result fixed:

PYTHONedit me
scores = {30, 10, 20, 10}
ranking = tuple(sorted(scores))
print(ranking)
OUTPUT
(10, 20, 30)

Read it from the inside out: first sorted() makes the list [10, 20, 30], then tuple() turns that list into a tuple.

Avoid: converting a single number

PYTHONedit me
print(list(5))
OUTPUT
TypeError: 'int' object is not iterable

"Iterable" means "something a for loop can go through". A number isn't a collection, so there are no items to pour out. If you want a list with one number in it, write [5].

list(), tuple() and set() pour the items into a new container. set() also drops the repeats.

your turnFill the gap

Turn the tuple into something you can append to

nums = (3, 1, 3) nums = ?(nums) nums.append(2) print(nums)

It should print: [3, 1, 3, 2]

Which piece makes this code work?
your turnType the output

Type what this prints

print(len(set("hello")))
Read the code line by line, then type the output exactly.

Collections Inside Collections

A collection can hold other collections: a list of tuples, a set of tuples, a dictionary of lists. This is how real programs keep real data.

Think of a filing cabinet: the drawers hold folders, and the folders hold cards. Each level is its own kind of container.

PYTHONedit me
visits = [("Sunny", "Mon"), ("Rocky", "Mon"), ("Sunny", "Mon")]
unique_visits = set(visits)
print(len(visits), len(unique_visits))
OUTPUT
3 2

Each visit is a tuple of a name and a day. The list keeps all three; the set keeps the same visit only once, because ("Sunny", "Mon") appears twice.

The one rule

A list, a tuple and a dictionary's values can hold anything. But a set item and a dictionary key must be a value that can't change: a number, a string or a tuple. Never a list:

PYTHONedit me
spots = {[1, 2], [3, 4]}
OUTPUT
TypeError: cannot use 'list' as a set element (unhashable type: 'list')

"Unhashable" is Python's word for "this can change, so I can't file it away safely". If a list inside a set changed later, the set could end up with two equal items. Use tuples instead:

PYTHONedit me
spots = {(1, 2), (3, 4), (1, 2)}
print(len(spots))
print((3, 4) in spots)
OUTPUT
2
True
Can it be...number, stringtuplelist, set, dictionary
an item of a list or a tupleyesyesyes
an item of a setyesyesno
a dictionary keyyesyesno

A tuple as a dictionary key

Two values together can be one key:

PYTHONedit me
distance = {("Pune", "Mumbai"): 150, ("Pune", "Goa"): 450}
print(distance[("Pune", "Goa")])
OUTPUT
450

A dictionary of lists

The values of a dictionary can be lists, and you can still append to them:

PYTHONedit me
marks = {"Sunny": [82, 90], "Rocky": [45]}
marks["Rocky"].append(60)
for name, scores in marks.items():
    print(name, sum(scores))
OUTPUT
Sunny 172
Rocky 105

In a set, or as a dictionary key, use a tuple, never a list.

your turnSpot the bug

Which line breaks?

One line stops this program. Tap it.
your turnPredict the output

What will this print?

pairs = {(1, 2), (2, 1), (1, 2)} print(len(pairs))
Your turn! What will this code show on the screen?

Practice: Which one?

Solve these to lock in what you learned in this topic. Each one runs in your browser.

  1. 127.Python Program to Convert a List into a Set and a TupleEasySolve
  2. 128.Python Program to Count Different Points Using a Set of TuplesMediumSolve
  3. 129.Python Program to Make a Class Attendance ReportHardSolve