Python- Day 13- Tuples in Python (_)
Lists are great for storing items that can change during a program, like users or characters in a game.
But when you need a list that can’t be changed, use a tuple. Tuples are immutable — they cannot be modified after being created.
Defining a Tuple :
A tuple looks like a list, but you use parentheses ()
instead of square brackets []
. You can access elements using indexes, just like with lists. For example:
dimensions = (200, 50)
print(dimensions[0]) # 200
print(dimensions[1]) # 50
If you try to change a value in a tuple, Python will give you an error because tuples can’t be modified:
dimensions[0] = 250 # TypeError: 'tuple' object does not support item assignment
Tuples with One Element :
To create a tuple with just one item, include a comma:
my_tuple = (3,)
Looping Through a Tuple :
You can loop over the items in a tuple just like you would with a list:
dimensions = (200, 50)
for dimension in dimensions:
print(dimension)
>>
200
50
Reassigning a Tuple :
While you can’t change the contents of a tuple, you can assign a new tuple to the same variable:
dimensions = (200, 50)
print("Original dimensions:")
for dimension in dimensions:
print(dimension)
dimensions = (400, 100)
print("\nModified dimensions:")
for dimension in dimensions:
print(dimension)
>>
Original dimensions:
200
50
Modified dimensions:
400
100
When to Use Tuples :
Use tuples when you need a set of values that shouldn’t change throughout the program, as they are simple and efficient.
If you found this guide helpful then do click on 👏 the button.
Follow for more Learning like this 😊
If there’s a specific topic you’re curious about, feel free to drop a personal note or comment. I’m here to help you explore whatever interests you!