Python Tutorial Series – Tuples

Another type of collection that Python provides support for is tuples.

Tuples

Tuples are used to store comma separated values enclosed in parentheses, example:

to_do_tuple = ('groceries', 'laundry', 'wash car', 'vacuum')

Note: If the tuple has only one element, a comma after the element is needed, example:

to_do_tuple = ('groceries',)

Tuples retain their order and, unlike lists, elements in a tuple may not be changed.
Tuple elements have a corresponding index value. Indexing starts at 0 and increases by 1. Elements are accessed by using their index value.
For example this would print the third element value in the tuple, which is ‘wash car’:

print(to_do_tuple[2])

Tuples may also be indexed with negative values starting at the last element. Reverse indexing starts at – 1 and decreases by -1. For example, this would also print the third element value in the tuple, which is ‘wash car’:

print(to_do_tuple[-2])

Tuples may be looped through by using the in keyword:

for item in to_do_tuple:

    print(item)

Python provides support for a couple of built in tuple functions. These functions are as follows:

count – Returns the number of elements in the tuple with the given input value. Example:

to_do_tuple.count('vacuum')

index – Returns the index of the input value. Example:

to_do_tuple.index('vacuum')

A couple of other useful Python methods for tuples are:

len – Returns the number of elements in a tuple. Example:

num = len(to_do_tuple)

min – Returns the item with the minimum value. Example:

to_do_tuple.min() # returns 'groceries

max – Returns the item with the maximum value. Example:

to_do_tuple.max() # returns 'wash car

tuple – Constructor used to create a tuple. Example:

new_tuple = tuple(('exercise', 'shovel snow'))

Slicing

Slicing, which is accessing ranges of collection items, works exactly the same way for tuples as it does for lists.
As review, slicing is done by indexing the tuple with a beginning index followed by a colon and an ending index. The beginning index is inclusive. The ending index is exclusive. Example:

Extract elements 2 – 3 which would be indexes 1 – 2.

extracted_tuple = to_do_tuple[1:3]

Using the original tuple, this returns: to_do_tuple[‘laundry’, ‘wash car’] which is:
[element 2, element 3] which is:
[index 1, index 2]

If the beginning index is not included, the slicing starts at the first element in the tuple.

extracted_tuple = to_do_tuple[:3] # returns to_do_tuple['groceries', 'laundry', 'wash car']

If the ending index is not included, the slicing ends at the last element in the tuple.

extracted_tuple = to_do_tuple[1:] # returns to_do_tuple['laundry', 'wash car', 'vacuum']

If neither the beginning index or ending index is included, the slicing starts at the first element and ends at the last element.

extracted_tuple = to_do_tuple[:] # returns to_do_tuple['groceries', 'laundry', 'wash car', 'vacuum']

More Python