Keyboard Shortcuts N Next post
P Previous post
S Save / unsave
R Read aloud
T Toggle theme
/ Focus search
Esc Close panels
🔥
Ready to read...
DATA STRUCTURES Module 3 - Data Structures Python Python Basics Python Programming: From Zero to Real-World Applications

Tuples - Immutable Sequences in Python

Reviewed & accurate
AI Summary

What You Will Learn

Beginner

  • What tuples are and when to use them
  • Tuple vs list differences
  • Tuple packing and unpacking
Terminalpython
# Creating tuples
point = (3, 4)
single = (42,)         # Single element (note the comma!)
empty = ()
no_parens = 1, 2, 3    # Parentheses optional

# Accessing (same as lists)
print(point[0])        # 3
print(point[-1])       # 4

# Slicing
print(point[0:2])      # (3, 4)

# Length
print(len(point))      # 2

Tuples vs Lists

AspectListTuple
MutabilityMutableImmutable
Syntax[1, 2, 3](1, 2, 3)
MethodsMany (append, sort...)Only count, index
SpeedSlowerFaster
MemoryMoreLess
Use as dict keyNoYes

Tuple Unpacking

Terminalpython
# Unpacking
x, y = (3, 4)
print(x)   # 3
print(y)   # 4

# Swap variables
a, b = 10, 20
a, b = b, a   # Swapped!

# Multiple return values
def min_max(numbers):
    return min(numbers), max(numbers)

lowest, highest = min_max([3, 1, 4, 1, 5, 9])
print(lowest, highest)   # 1 9
When to use tuples
Use tuples for: fixed collections (coordinates, RGB colors), dictionary keys, multiple return values, data that should not change. Use lists for everything else.

Practical Exercise

Create a tuple: point = (10, 20)
Access: print(point[0])
Try: point[0] = 5 - see the TypeError
Unpack: x, y = point
Create a tuple with one element: (42,)

Key Takeaways

  • Tuples are immutable - cannot be changed after creation.
  • Use (42,) for single-element tuple (comma required).
  • Faster and smaller than lists.
  • Can be used as dictionary keys (lists cannot).
  • Unpacking: x, y = (3, 4). Great for multiple returns.
Previously: Lesson 17 covered list methods.
Today: You learned: Tuples - the immutable cousin of lists.
Next: Lesson 19 covers dictionaries.
Test Your Knowledge
How did you find this?

Comments

Join the discussion! Sign in with your Google or Blogger account, or comment as Anonymous - no account needed. For quick questions, also reach me on Telegram @cytestch.

Comments