Tuple data structure is a list of values separated by a comma, just like a list, the difference is that a Tuple is immutable, you cannot modify tuples directly after it is created.
When to use Tuple
Below are some reasons why you might need to use the tuple
data structure instead.
This article is a continuation of Python Data Structures For Beginners
Let us explore tuple in more details... and in the end, solve a problem using tuple
data structure.
Topics covered in this post:
1. Creating a Tuple
2. Access Tuple Elements
3. Negative Indexing
4. Slicing Tuples in Python
5. Changing a Tuple
6. Deleting a Tuple
7. Tuple Methods
8. Tuple Code Challenge
# Different types of tuples
# Empty tuple
tuple = ()
# tuple can hold heterogeneous (different) data types
tuple = ("cat", [4, 3, 2], (1, 2, 3))
# Plain comma-separated values are tuples by default
tuple = 1234, 4321, 'hello!'
# single tuple
tuple = 'hello', # <== note trailing comma
# single tuple parenthesis
# it becomes just a string object without the trailing comma
tuple = ('hello',) #<== note trailing comma
# looks like tuple, but not a tuple
tuple = ('hello') # => <class 'str'>
So just like in the case of a list tuple is a sequence / ordered list and therefore we can access it by referencing the index position.
# Accessing tuple elements by indexing
tuple = (1234, 4321, 'hello!')
# access with index
tuple[0] # output => 1234
tuple[2] # output => 'hello!'
We can also access tuple values using negative indexing
# Access with negative indexing
tuple = (1234, 4321, 'hello!')
tuple[-1] # output => 'hello'
tuple[-3] # output => 1234
We can also access tuple values by slicing, here are some of the examples
fruits = ('orange', 'apple', 'pear', 'grapes', 'banana')
# beginning to end
fruits[:] # output => ('orange', 'apple', 'pear', 'grapes', 'banana')
# index 2 to 5th item
fruits[2:5] # output => ('pear', 'grapes', 'banana')
# remove last 2 items
fruits[:-2] # output => ('orange', 'apple', 'pear')
# return first 2 items
fruits[:2] # output => ('orange', 'apple')
# index 2 to the end
fruits[2:] # output => ('pear', 'grapes', 'banana')
# every nth item
fruits[::2] # output => ('orange', 'pear', 'banana')
# reverse list
fruits[::-1] # output => ('banana', 'grapes', 'pear', 'apple', 'orange')
Tuples are immutable which means it can't be changed once it is created, but if it contains a data type e.g a list which is mutable then that can be changed. let's see how that works.
# Changing tuple values
fruits = ('orange', [1,2,3])
# Attempt to change the immutable type
fruits[0] = 'pear' # output => TypeError: 'tuple' object does not support item assignment
# Change mutable list type
fruits[1][0] = 5
fruits # output => ('orange', [5, 2, 3])
Again deleting individual items in a tuple is not possible because it is immutable, but what you can do is delete the entire list, let's take another look.
# Deleting tuples
fruits = ('orange', [1,2,3])
# can't delete items
del fruits[0] # output => TypeError: 'tuple' object doesn't support item deletion
# Can delete the entire tuple
# deletes successfully
del fruits
Unlike List which has a hand. full of methods, tuple only has 2 in-built methods
count() - Total occurrence in a tuple
index() - Returns the position of where result was found
Now that we know what a tuple is and what it looks like, let's explore how to use it in solving a problem.
Given a word, compute the scrabble score for that word.
You'll need these:
```
Letter Value
A, E, I, O, U, L, N, R, S, T 1
D, G 2
B, C, M, P 3
F, H, V, W, Y 4
K 5
J, X 8
Q, Z 10
```
Using the above values, you can work out the points for a word.
"cabbage" should be scored as worth 14 points:
3 points for C
1 point for A, twice
3 points for B, twice
2 points for G
1 point for E
And to total:
`3 + 2*1 + 2*3 + 2 + 1`
= `3 + 2 + 6 + 3`
= 14
Solution Steps
# a list of heterogeneous (different) tuple types (int and string)
SCORES = [
(1, 'A, E, I, O, U, L, N, R, S, T'),
(2, 'D, G'),
(3, 'B, C, M, P'),
(4, 'F, H, V, W, Y'),
(5, 'K'),
(8, 'J, X'),
(10, 'Q, Z')
]
# sum up all values found
def score(word):
return sum([letter_scores(letter) for letter in word.upper()])
# for each letter given, search through the SCORES list for a value
def letter_scores(letter):
for score, letters in SCORES:
if letter in letters:
return score
Conclusion
Use tuples for heterogeneous (different) data types and lists for homogeneous (similar) data types. If data doesn't need to change during execution then use tuples.