0% found this document useful (0 votes)
5 views

Python Tuples

Uploaded by

abdulturay2002
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
5 views

Python Tuples

Uploaded by

abdulturay2002
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 5

Tuples

1. Introduction to Tuples
Definition

• A tuple is an ordered, immutable sequence of elements


• Represented by parentheses ()
• Can contain elements of different data types
• Similar to lists but immutable (cannot be changed after creation)

Creating Tuples
# Empty tuple
empty_tuple = ()

# Single element tuple (note the comma)


single_tuple = (1,) # Correct
not_tuple = (1) # This is an integer, not a tuple!

# Multiple elements
numbers = (1, 2, 3, 4, 5)
mixed_tuple = (1, "hello", 3.14, True)

# Tuple packing
coordinates = 3, 4 # Parentheses are optional

Why Use Tuples?

1. Immutability ensures data integrity


2. Slightly faster than lists
3. Can be used as dictionary keys (lists cannot)
4. Signal intent that data shouldn't change
5. Use less memory than lists

2. Accessing Tuples
Index-Based Access
coordinates = (4, 5, 6)

# Positive indexing (starts from 0)


print(coordinates[0]) # Output: 4
print(coordinates[1]) # Output: 5
# Negative indexing (starts from -1)
print(coordinates[-1]) # Output: 6
print(coordinates[-2]) # Output: 5

Slicing

numbers = (0, 1, 2, 3, 4, 5, 6, 7, 8, 9)

# Basic slicing [start:end:step]


print(numbers[2:5]) # Output: (2, 3, 4)
print(numbers[:4]) # Output: (0, 1, 2, 3)
print(numbers[6:]) # Output: (6, 7, 8, 9)
print(numbers[::2]) # Output: (0, 2, 4, 6, 8)
print(numbers[::-1]) # Output: (9, 8, 7, 6, 5, 4, 3, 2, 1, 0)

3. Working with Immutable Tuples


Attempting to Modify (Will Raise Error)
coordinates = (4, 5, 6)
coordinates[0] = 10 # TypeError: 'tuple' object does not support item

Workarounds for "Updating" Tuples


# 1. Convert to list, modify, convert back
coordinates = (4, 5, 6)
temp_list = list(coordinates)
temp_list[0] = 10
coordinates = tuple(temp_list)

# 2. Create new tuple


original = (1, 2, 3)
updated = (0,) + original[1:] # Creates new tuple (0, 2, 3)

4. Tuple Unpacking
Basic Unpacking
# Simple unpacking
x, y, z = (1, 2, 3)
print(x) # Output: 1
print(y) # Output: 2
print(z) # Output: 3

# Swapping values
a, b = 10, 20
a, b = b, a # Easy swap using tuple packing and unpacking

Advanced Unpacking
# Using * to capture multiple elements
first, *middle, last = (1, 2, 3, 4, 5)
print(first) # Output: 1
print(middle) # Output: [2, 3, 4]
print(last) # Output: 5

# Ignoring values with _


x, _, z = (1, 2, 3) # Ignoring middle value

5. Looping Through Tuples


Basic For Loop
colors = ('red', 'green', 'blue')

for color in colors:


print(color)

Enumerated Loop
colors = ('red', 'green', 'blue')

for index, color in enumerate(colors):


print(f"Color {index}: {color}")

Multiple Tuple Iteration

points = [(1, 2), (3, 4), (5, 6)]

for x, y in points:
print(f"X: {x}, Y: {y}")

6. Tuple Methods
Built-in Methods

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

# count() - returns number of occurrences


count_2 = numbers.count(2) # Returns: 3
# index() - returns first occurrence index
index_4 = numbers.index(4) # Returns: 5

# len() - returns tuple length


length = len(numbers) # Returns: 7

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

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

# Membership testing
print(2 in tuple1) # True
print(5 in tuple1) # False

7. Nested Tuples
Creating and Accessing Nested Tuples
# Creating nested tuples
matrix = ((1, 2, 3), (4, 5, 6), (7, 8, 9))

# Accessing elements
print(matrix[0]) # (1, 2, 3)
print(matrix[0][1]) # 2

# Nested unpacking
(a, b, c), (d, e, f), (g, h, i) = matrix

8. Practical Exercises
Exercise 1: Basic Tuple Operations
# Create a tuple of months
months = ('Jan', 'Feb', 'Mar', 'Apr', 'May')

# Tasks:
# 1. Print the third month
# 2. Slice the first three months
# 3. Check if 'Jul' exists in the tuple
Exercise 2: Tuple Unpacking

# Given a tuple of student data: (name, age, grade)


student = ('Alice', 20, 95.5)

# Tasks:
# 1. Unpack into variables
# 2. Print formatted string with all info

Exercise 3: Nested Tuples


# Given coordinates of a triangle
triangle = ((0, 0), (1, 0), (0, 1))

# Tasks:
# 1. Extract all x-coordinates
# 2. Calculate the perimeter
# 3. Print formatted coordinates

You might also like