0% found this document useful (0 votes)
3 views3 pages

Python Tuples

Uploaded by

23wh1db013
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views3 pages

Python Tuples

Uploaded by

23wh1db013
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

Python-Tuples:

Why do we need Tuples, when we already have Lists?

We know how to store multiple values using lists, which are mutable . but sometimes we
need data that should not be changed - like fixed details or database records.

Tuples: (The Read only list)


● Tuples are ordered and unchangeable (immutable) collections.
● It is written within round brackets ( ).
● Once created you cannot modify its elements.
● Performance is faster when compared to Lists.

● Creating a Tuple:
# Normal tuple
colors = ("red", "green", "blue")

# Tuple with mixed data


person = ("John", 25, "Engineer", 72.5)

# Tuple with one element


single = ("hello",)
print(type(single)) # <class 'tuple'>

# Without comma → treated as string


not_tuple = ("hello")
print(type(not_tuple)) # <class 'str'>
Always include a comma when creating a tuple with only one element.

● Accessing Tuple elements:


numbers = (10, 20, 30, 40, 50)

print(numbers[0]) # First element


print(numbers[-1]) # Last element
print(numbers[1:4]) # Slice

● Tuples are immutable:


numbers = (1, 2, 3)
# numbers[1] = 5 TypeError: 'tuple' object does not support
item assignment

● Reassigning the Entire Tuple:


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

● Tuple Operations:
t1 = (1, 2, 3)
t2 = (4, 5, 6)

# Concatenation
t3 = t1 + t2
print(t3)

# Repetition
t4 = t1 * 3
print(t4)

● Tuple Functions:
t = (5, 2, 8, 1, 9, 2)

print(len(t)) # Length
print(max(t)) # Largest
print(min(t)) # Smallest
print(sum(t)) # Sum
print([Link](2)) # Count of 2
print([Link](8)) # Index of 8

● Looping Through tuples:


colors = ("red", "green", "blue")
for color in colors:
print(color)

● Tuple packing and Unpacking :


# Packing
person = ("Alice", 22, "Designer")

# Unpacking
name, age, profession = person
print("Name:", name)
print("Age:", age)
print("Profession:", profession)
● Tuple vs List example:
# List can be modified
fruits_list = ["apple", "banana"]
fruits_list.append("mango")
print(fruits_list)

# Tuple cannot be modified


fruits_tuple = ("apple", "banana")
# fruits_tuple.append("mango") ❌ TypeError

● When to Use Tuples


1. When the data should not change.
2. When you want faster performance.
3. When you want to use it as a dictionary key (since tuples are hashable, lists
aren’t).

Example: Database record,Coordinates of a point, Date of Birth

You might also like