Tuples are cool!
In Python, tuples and namedtuples are two unordered collections of immutable objects.
Tuples can be created using the tuple() constructor.
Tuples are used to store collections of data. Let's see an example:
empty_tuple = () # creates an empty tuple another_empty_tuple = tuple() # creates another empty tuple type(empty_tuple) # returns <class 'tuple'> empty_typle == another_empty_tuple # returns True
Initialising a tuple with values
A tuple can be initialised with default values placed between the square brackets or by invoking the
even_numbers = (2, 4, 6, 8, 10) odd_numbers = (1, 3, 5, 7, 9) sequence_list = tuple(1, 2, 3, 4) # new list with default values being assigned
Accessing individual items from a tuple
Items can be accessed using the indexing/slicing notation. If you try to access an item which is not present in the tuple, an
IndexError will be raised.
numbers = (1, 10, 100, 1000, 10000) numbers # first element in the tuple, returns 1 numbers # second element in the tuple, returns 10 numbers[-1] # last element in the tuple, return 10000 numbers # returns IndexError: tuple index out of range
Adding new items to a tuple
Tuples do not have any built-in members and therefore we can make use of the
+ operator to add an item to an existing tuple. Note the extra
comma at the end of the tuple list.
a = () id(a) # returns a unique id a = a + (2,) a = a + (3,) a # returns (2, 3) id(a) # returns another unique id proving that tuples are immutable
Remove items from a tuple
As tuples are
immutable, so once a tuple is created, there is no way to modify that tuple. One way to remove an item from a tuple is to convert the tuple to list, remove the item and then convert it back to a tuple:
a = (2, 3) # new tuple with 2 and 3 as values b = list(a) # convert to list b.remove(3) # remove 3 from the list a = tuple(b) # a is now (3,)
Membership testing in tuples
in operator is used to demonstrate membership testing in Python and it's quite central when using tuples to check for items being present in a specific tuple. Using the
in operator will always return a boolean result.
Here's an example:
a = (1, 2, 3, 4) 5 in a # returns False 3 in a # returns True
Counting items in a tuple
We can use Python's in-built
len() method to count the total number of items in a tuple.
a = (1, 2, 3, 4) len(a) # returns 4
Finding the posiiton of an item
We can use
dict.index() method to find the position of an item in a tuple. Note that only the first occurence's index will be shown:
a = (1, 2, 3, 4, 1) a.index(1) # returns 0 a.index(3) # returns 2
Counting the exact occurences of an item in a tuple
One can make use of the
tuple.count() method to count the number of occurences of an item in a tuple.
a = (1, 2, 3, 4, 5, 1) a.count(1) # returns 2, there are 2 instances of the number 1 being present in the tuple.
Extending items in a tuple
+ operator method allows a tuple to extend or concatenate its result set to another tuple.
a = (1, 2, 3) b = (3, 4, 5) a + b # returns (1, 2, 3, 3, 4, 5)
Sorting items in a tuple
The sorted() method creates a new sorted tuple from an iterable and works for other types other than tuples. As
sorted returns a list, we'll need to convert it back to a tuple. Let's see an example:
students = ("Mark", "Tom", "John", "Oz") tuple(sorted(students)) # returns ('John', 'Mark', 'Oz', 'Tom')
We have a slight problem when we have to sort items which in turn have both lower and uppercase characters.
fruits = ('apples', 'Bananas', 'oranges', 'Pears', 'Apples') tuple(sorted(fruits)) # returns ('Apples', 'Bananas', 'Pears', 'apples', 'oranges')
As we can see, the lowercase
oranges did not get properly sorted to our liking.
To solve this issue, we can make use of a key function.
fruits = ('apples', 'Bananas', 'oranges', 'Pears', 'Apples') tuple(sorted(fruits, key=lambda v: v.upper())) # returns ['apples', 'Apples', 'Bananas', 'oranges', 'Pears']
Awesome, isn't it?? Using the lambda function defined in the key allowed us to specify in which order the values will be returned.
Now what if we wanted the uppercase values first? Hmm..let's see how we can solve this one:
fruits = ('apples', 'Bananas', 'oranges', 'Pears', 'Apples') tuples(sorted(fruits, key=lambda v: (v.upper(), v.islower()))) # returns ('Apples', 'apples', 'Bananas', 'oranges', 'Pears')
We have not really talked much about
lambdas so far but we'll get to this in a future tutorial.
named tuple is very much similar to a tuple. It is indexable, iterable and is a subclass of tuple.
A named tuple can prove to be really useful when we want to make our code more readable but at the same time, do not want to create a custom object.
Named tuples have to be imported from the
collections module in Python.
Let's see an example:
from collections import namedtuple Headlight = namedtuple('Headlight', ['left, right']) # create a namedtuple instance supporting 2 fields(left, right). bmw_headlight = Headlight('Full', 'Half') bmw_headlight # returns Full bmw_headlight # returns Half bmw_headlight.left # returns Full bmw_headlight.right # returns Half
Do you use tuples or named tuples in Python or want to suggest an improvement to this article? Please share it with us by leaving a reply below.
Part 2 coming soon. Stay tuned!