Tuples in Python

 

What is a Tuple? 

A tuple in Python is like a list, but immutable (unchangeable). Think of it as a shopping receipt —you can't modify what's already printed!

Why Use Tuples?

  • Faster than lists 
  • Protects data from accidental changes 
  • Can be used as dictionary keys 

Creating a Tuple

Tuples are created using parentheses ().

tuple_example = ("apple", "banana", "cherry")
print(tuple_example)  # Outputs: ('apple', 'banana', 'cherry')

Single-Item Tuple? 

If a tuple has only one item, you must add a comma , at the end.

single_item = ("apple",)  # Tuple 
not_a_tuple = ("apple")   # Just a string 

Accessing Tuple Items

Works just like lists!

print(tuple_example[0])  # Outputs: apple
print(tuple_example[-1])  # Outputs: cherry

Tuples are Immutable!

Once created, you can't change tuple elements.

tuple_example[1] = "mango"  # Error! Tuples cannot be modified

Tuple Methods

Even though tuples are immutable, they have some useful methods.

count() – Counts occurrences of an item:

tuple_numbers = (1, 2, 3, 2, 2, 4)
print(tuple_numbers.count(2))  # Outputs: 3

index() – Finds the index of an item:

print(tuple_numbers.index(3))  # Outputs: 2

Looping Through a Tuple

You can loop through a tuple just like a list.

for item in tuple_example:
    print(item)

Summary 

Concept Description
Tuple Ordered, immutable collection of items
Indexing Access items using index numbers
Immutability Cannot be modified after creation
Methods .count(), .index()

 

Post a Comment

0 Comments