Tuples in Python: Immutable and Powerful


In Python, a tuple is a built-in data structure used to store a collection of items. Unlike lists, tuples are immutable, meaning once created, their contents cannot be changed. Tuples are great when you want to ensure your data stays constant throughout the program.
Let’s dive into the details.
Starting with Tuples
Fire up your Python shell and create your first tuple:
lang = ("c++", "javascript", "python")
You can access individual elements using indexing:
print(lang[1]) # Outputs: javascript
print(lang[-1]) # Outputs: python
Just like lists, tuples support slicing:
print(lang[1:]) # Outputs: ('javascript', 'python')
Tuples Are Immutable
Unlike lists, you cannot change elements in a tuple:
lang[0] = "java"
# ❌ Throws Error: 'tuple' object does not support item assignment
Basic operations on tuple
You can get the number of elements using len()
:
print(len(lang)) # Outputs: 3
Merging tuples:
You can concatenate tuples using the +
operator:
advance_lang = ("rust", "ruby", "golang")
all_lang = advance_lang + lang
print(all_lang)
# Outputs: ('rust', 'ruby', 'golang', 'c++', 'javascript', 'python')
Membership check:
You can check if a value exists in the tuple:
all_lang = ('rust', 'ruby', 'golang', 'c++', 'javascript', 'python')
if "ruby" in all_lang:
print("This tuple contains ruby")
# Outputs: This tuple contains ruby
Counting Elements:
Use .count()
to count how many times an element appears:
new_lang = ("c#", "kotlin", "c#")
print(new_lang.count("c#")) # Outputs: 2
print(new_lang.count("flutter")) # Outputs: 0
Nested tuples:
Tuples can contain other tuples — called nesting:
nested_tup = ("oops", "dbms", ("c++", "javascript", "python"), "os")
print(nested_tup)
# Outputs: ('oops', 'dbms', ('c++', 'javascript', 'python'), 'os')
Unpacking Tuples
You can unpack tuple values into variables:
lang = ("c++", "javascript", "python")
(Cpp, Js, Py) = lang
print(Cpp) # Outputs: c++
Summary
✅ Tuples are immutable
✅ They support indexing, slicing, unpacking, and nesting
✅ Use
.count()
andin
to explore data✅ Great for representing fixed collections
Stay tuned for the next post where we explore more data structures in Python!
Subscribe to my newsletter
Read articles from Harsh Gupta directly inside your inbox. Subscribe to the newsletter, and don't miss out.
Written by

Harsh Gupta
Harsh Gupta
I am a CSE undergrad learning DevOps and sharing what I learn.