What Are Tuples in Python? See Examples in detail

Tuples in Python are used to store multiple values in a single variable, similar to lists. However, unlike lists, tuples are ordered and immutable, meaning their values cannot be changed after creation.

Tuples are written using parentheses ().


Why Tuples Are Important

Tuples are useful when:

  • Data should not be modified
  • You need faster access than lists
  • Ensuring data integrity
  • Using values as dictionary keys

Example:

coordinates = (10, 20)

Creating a Tuple in Python

numbers = (1, 2, 3)
names = ("Aman", "Neha", "Ravi")
mixed = (1, "Python", True)

Tuple with One Item

To create a tuple with a single item, include a comma.

single = (5,)

Accessing Tuple Items

print(names[0])
print(names[-1])

Indexing works the same as lists.


Looping Through a Tuple

for name in names:
    print(name)

Immutability of Tuples

Once a tuple is created, its values cannot be changed.

numbers[0] = 10  # Error

Tuple Methods

Tuples have limited methods.

MethodDescription
count()Returns number of occurrences
index()Returns index of value

Example:

numbers = (1, 2, 2, 3)
print(numbers.count(2))

Tuple Packing and Unpacking

data = (10, 20, 30)
a, b, c = data

Tuple vs List

TupleList
ImmutableMutable
FasterSlightly slower
Uses ()Uses []

Conclusion

Tuples are ideal when you want to store fixed data that should not change. They improve performance and protect data integrity in Python programs.


References

Leave a Comment

Comments

No comments yet. Why don’t you start the discussion?

Leave a Reply

Your email address will not be published. Required fields are marked *