✓ Tuples in Python
✅ 1. Introduction to Tuples
• A tuple is a collection of ordered, immutable (unchangeable) elements.
• Tuples are written with round brackets ().
• Example:
python
CopyEdit
my_tuple = (10, 20, 30)
✅ 2. Creating Tuples
• Tuples can hold any data type and mixed data types.
python
CopyEdit
t1 = (1, 2, 3) # Integers
t2 = ("apple", "mango") # Strings
t3 = (1, "apple", 3.5) # Mixed types
t4 = () # Empty tuple
t5 = (5,) # Single-element tuple (comma is required!)
✅ 3. Tuple Assignment
• You can assign values of a tuple to multiple variables.
python
CopyEdit
(a, b, c) = (10, 20, 30)
print(a) # 10
print(b) # 20
print(c) # 30
✅ 4. Tuple Functions
• Common built-in functions used with tuples:
python
CopyEdit
t = (5, 1, 9, 5, 2)
print(len(t)) #5
print(max(t)) #9
print(min(t)) #1
print(t.count(5)) # 2 (count how many times 5 appears)
print(t.index(9)) # 2 (position of 9)
✅ 5. Indexing & Slicing
• Like strings and lists, tuples support indexing and slicing:
python
CopyEdit
t = (10, 20, 30, 40, 50)
print(t[0]) # 10 (first element)
print(t[-1]) # 50 (last element)
print(t[1:4]) # (20, 30, 40)
✅ 6. Tuples as Return Values
• Functions can return multiple values using tuples:
python
CopyEdit
def get_values():
return (10, 20, 30)
result = get_values()
print(result) # (10, 20, 30)
a, b, c = get_values()
print(a, b, c) # 10 20 30
✅ 7. Random Numbers
• Use the random module to create random tuples or choose from tuples.
python
CopyEdit
import random
t = (10, 20, 30, 40)
print(random.choice(t)) # Randomly prints one item from the tuple
✅ 8. Counting
• Use .count(value) to count occurrences of a value in a tuple:
python
CopyEdit
t = (1, 2, 2, 3, 2, 4)
print(t.count(2)) # 3
✅ 9. Operations on Tuples
• Concatenation: Combine tuples using +
python
CopyEdit
t1 = (1, 2)
t2 = (3, 4)
t3 = t1 + t2
print(t3) # (1, 2, 3, 4)
• Repetition: Repeat a tuple using *
python
CopyEdit
t = (5, 6)
print(t * 3) # (5, 6, 5, 6, 5, 6)