← Back to Python

All Topics

Advertisement

Learn/Python/Python Fundamentals

Tuples

Topic: Data Structures

Advertisement

Introduction

Tuples are ordered, immutable collections. They're similar to lists but cannot be modified after creation.

Creating Tuples

# Basic tuple
point = (3, 4)
colors = ("red", "green", "blue")

# Single element (needs comma)
single = (42,)

# Tuple unpacking
x, y = point
a, b, c = colors

Tuple Operations

coords = (10, 20, 30)

# Accessing
print(coords[0])      # 10
print(coords[1:3])    # (20, 30)

# Count and index
print(coords.count(10))
print(coords.index(20))

# Membership
print(20 in coords)   # True

Named Tuples

from collections import namedtuple

Point = namedtuple('Point', ['x', 'y'])
p = Point(3, 4)
print(p.x, p.y)

Practice Problems

  1. Swap values using tuple unpacking
  2. Return multiple values from function
  3. Use tuple as dictionary keys
  4. Convert between list and tuple
  5. Implement immutable data structure with named tuples

Advertisement

Advertisement

Need More Practice?

Get personalized Python help from ChatWhole's AI-powered platform.

Get Expert Help →