Virtual assistance

Python Tuples

Tuples are immutable, ordered sequences of elements. They are similar to lists but cannot be modified after creation.

Python Tuples

What are Tuples?

Tuples are immutable sequences, typically used to store collections of heterogeneous data. They are defined using parentheses () and elements are separated by commas.

"Tuples are immutable lists."

Creating Tuples

# Empty tuple
empty_tuple = ()

# Tuple with elements
numbers = (1, 2, 3, 4, 5)
fruits = ("apple", "banana", "cherry")
mixed = (1, "hello", 3.14, True)

# Single element tuple (note the comma)
single = (42,)
not_tuple = (42)  # This is just 42

print(type(single))   # <class 'tuple'>
print(type(not_tuple)) # <class 'int'>

Tuple Operations

fruits = ("apple", "banana", "cherry")

# Indexing
print(fruits[0])   # 'apple'
print(fruits[-1])  # 'cherry'

# Slicing
print(fruits[1:3]) # ('banana', 'cherry')

# Concatenation
tuple1 = (1, 2, 3)
tuple2 = (4, 5, 6)
combined = tuple1 + tuple2
print(combined)  # (1, 2, 3, 4, 5, 6)

# Repetition
repeated = (1, 2) * 3
print(repeated)  # (1, 2, 1, 2, 1, 2)

# Membership
print("apple" in fruits)  # True
print(len(fruits))        # 3

Tuple Methods

Tuples have fewer methods than lists due to their immutability:

numbers = (1, 2, 3, 2, 4, 2)

# count() - Count occurrences
print(numbers.count(2))  # 3

# index() - Find first index
print(numbers.index(3))  # 2

# index() with start and end
print(numbers.index(2, 2, 5))  # 3

When to Use Tuples

  • Data Integrity: When you want to ensure data cannot be modified
  • Dictionary Keys: Tuples can be used as dictionary keys (lists cannot)
  • Function Returns: Returning multiple values from functions
  • Unpacking: Tuple unpacking is commonly used
  • Performance: Slightly faster than lists for iteration

Tuple Unpacking

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

# Extended unpacking
numbers = (1, 2, 3, 4, 5)
first, *middle, last = numbers
print(first)   # 1
print(middle)  # [2, 3, 4]
print(last)    # 5

# Swapping values
a, b = 1, 2
a, b = b, a
print(a, b)  # 2 1

Named Tuples

Named tuples provide a way to create tuple subclasses with named fields:

from collections import namedtuple

# Define a named tuple
Point = namedtuple('Point', ['x', 'y'])
Person = namedtuple('Person', 'name age city')

# Create instances
p1 = Point(3, 4)
person1 = Person('Alice', 25, 'New York')

print(p1.x, p1.y)           # 3 4
print(person1.name)         # 'Alice'
print(person1.age)          # 25

# Convert to dictionary
print(person1._asdict())    # {'name': 'Alice', 'age': 25, 'city': 'New York'}

Tuples vs Lists

AspectTuplesLists
MutabilityImmutableMutable
Syntax()[]
MethodsFewer methodsMany methods
MemoryLess memoryMore memory
PerformanceFasterSlower
Use caseFixed dataChanging data

Tuples are perfect when you need an immutable sequence of items. They provide data integrity and can be used as dictionary keys, making them valuable in many Python programs.