Write Python. Understand every error.

Starting Python in your browser…

Python basics · topic 12 of 25

Tuples and sets

A tuple is like a list that cannot be changed. It is written with round brackets. Tuples are useful for values that belong together, such as coordinates or a date.

point = (3, 4)
x, y = point      # unpacking
print(x, y)

A set stores unique values with no fixed order, written with curly brackets. Adding a value that is already present has no effect, so sets are a quick way to remove duplicates.

nums = [3, 1, 3, 2, 1]
print(set(nums))       # {1, 2, 3}
print(len(set(nums)))  # 3

Sets support maths-style operations: a | b is the union, a & b the items in both, and a - b the items only in a. Use sorted() to print a set in a predictable order.

Key takeaways

  • A tuple is like a list that cannot be changed. It is written with round brackets.
  • A set keeps one copy of each value and has no fixed order, which makes it a quick way to remove duplicates.
  • Sets support | (union), & (in both) and - (only in the first).
  • A one-item tuple needs a comma: (5,) is a tuple, but (5) is just the number 5.

Common mistakes

  • Trying to change a tuple item, as in t[0] = 9. Read the TypeError guide.
  • Writing {} and expecting an empty set. It makes an empty dictionary, so use set().
  • Expecting a set to keep the order you typed. Use sorted() to print it in a predictable order.

Practise with these programs

Share this page:

Ctrl + Enter to run
Line 1, column 1Tab indents 4 spaces. Press Esc then Tab to leave the editor.