Tuples

15 min In Progress

Learning Objectives

  • Understand immutable sequences
  • Use tuples for fixed data
  • Unpack tuples into variables

Tuple Basics

Tuples are like lists but immutable. Once created, they cannot be changed.

point = (10, 20)
print(point[0])
# point[0] = 15  # This would raise an error

Tuple Unpacking

Assign tuple elements directly to variables.

coords = (3, 4)
x, y = coords
print(x, y)

Course Example: Pet Analysis

Using tuple methods to analyze data.

pets = ("cat", "cat", "cat", "dog", "horse")
c = pets.count("cat")
d = len(pets)
if (c/d)*100 > 50.0:
  print("There are too many cats here")
else:
  print("Everything is good")

📝 Exercise: Coordinate Swap

Create a tuple with two numbers. Use unpacking to swap their values and print both.

code.py
Output

            
← Back to Chapter