Lesson 41 +10 XP

Tuples

Tuples

A tuple is like a list, but unchangeable. Once you make one, you can't add, remove, or change items.

Create a tuple

thistuple = ("apple", "banana", "cherry")
print(thistuple)

Tuple properties

  • Ordered: items keep their order.
  • Unchangeable: no add, remove, or change after creation.
  • Allow duplicates: the same value can appear more than once.

One item needs a trailing comma

thistuple = ("apple",)
print(type(thistuple))  # <class 'tuple'>

Without the comma, ("apple") is just the string "apple".

Access items

Indexing works exactly like a list:

print(thistuple[0])    # apple
print(thistuple[-1])   # cherry

Length

print(len(thistuple))  # 3

Mixed types

mixed = (1, "two", 3.0, True)

Why use tuples?

  • They protect data from accidental changes.
  • They're faster than lists.
  • They can be used as dictionary keys (lists can't).

TL;DR

  • Tuples use ( ) and are unchangeable.
  • They allow duplicates and are ordered.
  • One-item tuples need a trailing comma.
  • Good for data that shouldn't change.