📌

How to Use Tuples in Python

PythonBeginner

Create immutable sequences with tuples.

Code Example

Python
# Tuples in Python
coordinates = (10, 20)
print(f"Coordinates: {coordinates}")
print(f"X: {coordinates[0]}, Y: {coordinates[1]}")

# Tuple unpacking
x, y = coordinates
print(f"\nUnpacked: x={x}, y={y}")

# Tuple with multiple values
person = ("Alice", 25, "Engineer")
name, age, job = person
print(f"\n{name} is {age} years old, works as {job}")

# Tuples are immutable
try:
    coordinates[0] = 30
except TypeError as e:
    print(f"\nError: {e}")

# Tuple methods
numbers = (1, 2, 2, 3, 2, 4)
print(f"\nCount of 2: {numbers.count(2)}")
print(f"Index of 3: {numbers.index(3)}")

Explanation

Tuples are immutable sequences. Use parentheses to create them. Great for returning multiple values from functions.

Related Tutorials