Python - tutorial - 05/14

tuples

Revision:


Python - tuples

Tuples are used to store multiple items in a single variable. A tuple is a collection which is ordered and unchangeable. Tuples are written with round brackets.

Example 1: create a tuple

        thistuple = ("apple", "banana", "cherry")
        print(thistuple)
    

Tuple items are ordered, unchangeable, and allow duplicate values. Tuple items are indexed, the first item has index [0], the second item has index [1] etc.

Ordered: the items have a defined order, and that order will not change.

Unchangeable: we cannot change, add or remove items after the tuple has been created.

Allow duplicates: since tuples are indexed, they can have items with the same value.

Example 2: tuples allow duplicate values:

        thistuple = ("apple", "banana", "cherry", "apple", "cherry")
        print(thistuple)
    

Tuple length: to determine how many items a tuple has, use the len() function.

Example 3: print the number of items in the tuple:

        thistuple = ("apple", "banana", "cherry")
        print(len(thistuple))  # 3
    

Create tuple with one item: to create a tuple with only one item, you have to add a comma after the item, otherwise Python will not recognize it as a tuple.

Example 4: one item tuple, remember the commma:

        thistuple = ("apple",)
        print(type(thistuple)) # class 'tuple'

        #NOT a tuple
        thistuple = ("apple")
        print(type(thistuple)) # class 'str'
    

Tuple items - data types: tuple items can be of any data type. A tuple can contain different data types.

Example 5: string, int, and boolean data types:

        tuple1 = ("apple", "banana", "cherry")
        tuple2 = (1, 5, 7, 9, 3)
        tuple3 = (True, False, False)
    

Example 6: a tuple with strings, integers, and boolean values:

        tuple1 = ("abc", 34, True, 40, "male")
    

type(): from Python's perspective, tuples are defined as objects with the data type 'tuple'.

The tuple() constructor can also be used to make a tuple.

Example 7: using the tuple() constructor to make a set:

        thistuple = tuple(("apple", "banana", "cherry")) # note the double round-brackets
        print(thistuple)
    

Python collections (arrays): There are four collection data types in the Python programming language:

List is a collection which is ordered and changeable. Allows duplicate members.
Tuple is a collection which is ordered and unchangeable. Allows duplicate members.
Set is a collection which is unordered and unindexed. No duplicate members.
Dictionary is a collection which is ordered and changeable. No duplicate members.


Python - access tuple items

Access tuple items can be accessed by referring to the index number, inside square brackets. Negative indexing, which starts from the end, is also possible: -1 refers to the last item, -2 refers to the second last item, etc.

Example 8: print the second item in the tuple:

        thistuple = ("apple", "banana", "cherry")
        print(thistuple[1])
    

Example 9: print the last item of the tuple:

        thistuple = ("apple", "banana", "cherry")
        print(thistuple[-1])
    

Range of indexes: you can specify a range of indexes by specifying where to start and where to end the range. When specifying a range, the return value will be a new tuple with the specified items. By leaving out the start value, the range will start at the first item. By leaving out the end value, the range will go on to the end of the list.

Example 10: return the third, fourth, and fifth item:

        thistuple = ("apple", "banana", "cherry", "orange", "kiwi", "melon", "mango")
        print(thistuple[2:5])
    

Example 11: his example returns the items from the beginning to, but NOT included, "kiwi":

        thistuple = ("apple", "banana", "cherry", "orange", "kiwi", "melon", "mango")
        print(thistuple[:4])
    

Example 12: this example returns the items from "cherry" and to the end:

        thistuple = ("apple", "banana", "cherry", "orange", "kiwi", "melon", "mango")
        print(thistuple[2:])
    

Range of negative indexes: specify negative indexes if you want to start the search from the end of the tuple:

Example 13: This example returns the items from index -4 (included) to index -1 (excluded)

        thistuple = ("apple", "banana", "cherry", "orange", "kiwi", "melon", "mango")
        print(thistuple[-4:-1]) # ('orange', 'kiwi', 'melon')
    

Check if item exists: to determine if a specified item is present in a tuple use the "in" keyword:

Example 14: check if "apple" is present in the tuple:

        thistuple = ("apple", "banana", "cherry")
        if "apple" in thistuple:
            print("Yes, 'apple' is in the fruits tuple")
    


Python - update tuples

Tuples are unchangeable, meaning that you cannot change, add, or remove items once the tuple is created. But there are some workarounds.

Change tuple values: you can convert the tuple into a list, change the list, and convert the list back into a tuple.

Example 15: convert the tuple into a list to be able to change it:

        x = ("apple", "banana", "cherry")
        y = list(x)
        y[1] = "kiwi"
        x = tuple(y)
        print(x) # ("apple", "kiwi", "cherry")
    

Add items: convert the tuple into a list, add your item(s), and convert it back into a tuple.

Example 16: convert the tuple into a list, add "orange", and convert it back into a tuple:

        thistuple = ("apple", "banana", "cherry")
        y = list(thistuple)
        y.append("orange")
        thistuple = tuple(y) 
        print(thistuple) # ('apple', 'banana', 'cherry', 'orange')
    

Remove items: you can use the same workaround as we used for changing and adding tuple items. Or you can delete the tuple completely.

Example 17: convert the tuple into a list, remove "apple", and convert it back into a tuple:

        thistuple = ("apple", "banana", "cherry")
        y = list(thistuple)
        y.remove("apple")
        thistuple = tuple(y) 
        print(thistuple) # ('banana', 'cherry')
    

Example 18: the "del" keyword can delete the tuple completely:

        thistuple = ("apple", "banana", "cherry")
        del thistuple
        print(thistuple) #this will raise an error because the tuple no longer exists
    


Python - unpack tuples

Unpacking a tuple: when we create a tuple, we normally assign values to it. This is called "packing" a tuple. But, in Python, we are also allowed to extract the values back into variables. This is called "unpacking".

Example 19: unpacking a tuple:

        fruits = ("apple", "banana", "cherry")
        (green, yellow, red) = fruits
        print(green) # apple
        print(yellow) # banana
        print(red) # cherry
    

The number of variables must match the number of values in the tuple, if not, you must use an asterix to collect the remaining values as a list.

Using asterisk (*): if the number of variables is less than the number of values, you can add an * to the variable name and the values will be assigned to the variable as a list. If the asterix is added to another variable name than the last, Python will assign values to the variable until the number of values left matches the number of variables left.

Example 20: assign the rest of the values as a list called "red":

        fruits = ("apple", "banana", "cherry", "strawberry", "raspberry")
        (green, yellow, *red) = fruits
        print(green) # apple
        print(yellow) # banana
        print(red)  # ['cherry', 'strawberry', 'raspberry']
    

Example 21: add a list of values to the "tropic" variable:

        fruits = ("apple", "mango", "papaya", "pineapple", "cherry")
        (green, *tropic, red) = fruits
        print(green) # apple
        print(tropic) # ['mango', 'papaya', 'pineapple']
        print(red) # cherry
    


Python - loop tuples

Loop through a tuple: you can loop through the tuple items by using a "for" loop.

Example 22: iterate through the items and print the values:

        thistuple = ("apple", "banana", "cherry")
        for x in thistuple:
            print(x) # apple banana cherry
    

Loop through the index numbers: you can also loop through the tuple items by referring to their index number. Use the range() and len() functions to create a suitable iterable.

Example 23: print all items by referring to their index number:

        thistuple = ("apple", "banana", "cherry")
        for i in range(len(thistuple)):
            print(thistuple[i]) # apple banana cherry
    

Using a while loop: you can loop through the list items by using a while loop. Use the len() function to determine the length of the tuple, then start at 0 and loop your way through the tuple items by refering to their indexes. Remember to increase the index by 1 after each iteration.

Example 24: print all items, using a while loop to go through all the index numbers:

        thistuple = ("apple", "banana", "cherry")
        i = 0
        while i < len(thistuple):
            print(thistuple[i])
            i = i + 1
    


Python - join tuples

Join two tuples: to join two or more tuples you can use the "+" operator:

Example 25: join two tuples:

        tuple1 = ("a", "b" , "c")
        tuple2 = (1, 2, 3)
        tuple3 = tuple1 + tuple2
        print(tuple3) # ('a', 'b', 'c', 1, 2, 3)
    

Multiply tuples: if you want to multiply the content of a tuple a given number of times, you can use the "*" operator:

Example 26: multiply the fruits tuple by 2:

        fruits = ("apple", "banana", "cherry")
        mytuple = fruits * 2
        print(mytuple) # ('apple', 'banana', 'cherry', 'apple', 'banana', 'cherry')
    


Python - tuple methods

Tuple methods: Python has two built-in methods that you can use on tuples.

Method - Description
count() - Returns the number of times a specified value occurs in a tuple
index() - Searches the tuple for a specified value and returns the position of where it was found