Login With Github

Python 3 Tuple Starter Tutorial

In the previous section, we got to know the list in Python. Python provides another type that is an ordered collection of objects, called a tuple. The main difference between the tuples and the lists is that the tuples cannot be changed unlike lists.

How To Define Tuples

We can define tuples with parentheses, the example code looks like this:

coral = ('blue coral', 'staghorn coral', 'pillar coral', 'elkhorn coral')
mixed = ('physics', 'chemistry', 1997, 2000)
numbers = (1, 2, 3, 4, 5 )

We can use two parentheses containing nothing to define an empty tuple:

emptyTuple = ();

When a tuple contains only one element, you need to add a comma after the element, otherwise the parentheses will be used as operators:

>>>tup1 = (50)
>>> type(tup1)     # the type is integer without a comma
<class 'int'>
 
>>> tup1 = (50,)
>>> type(tup1)     # the type is tuple with a comma
<class 'tuple'>

As mentioned before, the values of tuples can not be modified. So, when you use tuples in your python programs, you should convey to others in the code that you do not wish to modify the tuple values. In addition, because of this feature, we can also use tuples to optimize Python code, as the code will be slightly faster for tuples than for lists.

How To Access Tuples

Like strings and lists, we can also use square brackets to get the elements in a tuple. To be precise, everything you've learned about lists is true of tuples as well, but they can't be modified. That is, tuples can contain arbitrary objects, tuples can be indexed and sliced, tuples can be nested etc.

Indexing Tuples

Each element in the tuple has a corresponding index number, which is an integer value, starting with the index number 0.

For example, the element of the mixed tuple defined above and its index are as follows:

'physics' 'chemistry' 1997 2000
0 1 2 3

Because each item in a Python tuple has a corresponding index number, we're able to access items. Let's print the first item of mixed tuple:

print(mixed[0])

The output is as follows:

physics

For mixed tuple, its index number range is 0-3. This means that if the index number is greater than 3, the program will throw an exception. For example:

print(mixed[10])

#Output
IndexError: tuple index out of range

Like Python list, the tuple's index number can also be negative, which is started at -1. This is especially useful if we have a long tuple and we want to pinpoint an item towards the end of a tuple.

For the same tuple mixed, the negative index breakdown looks like this:

'physics' 'chemistry' 1997 2000
-4 -3 -2 -1

So, let's print the item "chemistry":

print(mixed[-3])

#Output
chemistry

Slicing Tuples

We can use indexing to call out a few items from the tuple. Slices allow us to call multiple values by creating a range of index numbers separated by a colon [x:y].

Let's say we would like to just print the middle items of mixed, we can do so by creating a slice.

print(mixed[1:3])

#Output
('chemistry', 1997)

Note: The first number in brackets is the beginning (inclusive) of the slice, and the second number is the end of the slice (exclusive), which is why in our example above the items at position, 1 and 2 are the items that print out.

we can get items from beginning to end with the following syntax:

print(mixed[:])

#Output
('physics', 'chemistry', 1997, 2000)

Like python list, we can also specify the slicing increment by k in a[m:n:k]. For example:

numbers = (0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12)

print(numbers[1:11:2])

#Output
(1, 3, 5, 7, 9)

Our construction numbers[1:11:2] prints the values between index numbers inclusive of 1 and exclusive of 11, then the stride value of 2 tells the program to print out only every other item.

We can omit the first two parameters and use stride alone as a parameter with the syntax tuple[::z]:

print(numbers[::3])

#Output
(0, 3, 6, 9, 12)

Tuples Assignment, Packing, and Unpacking

As mentioned above, you can assign a tuple containing multiple text items to a single object:

>>> t = ('foo', 'bar', 'baz', 'qux')

This situation is like the items in the tuple have been "packaged" into the object:

>>> t
('foo', 'bar', 'baz', 'qux')
>>> t[0]
'foo'
>>> t[-1]
'qux'

If that "packed" object is subsequently assigned to a new tuple, the individual items are "unpacked" into the objects in the tuple:

>>> (s1, s2, s3, s4) = t
>>> s1
'foo'
>>> s2
'bar'
>>> s3
'baz'
>>> s4
'qux'

In this section, the images and codes about tuple pack/unpack are referenced from realpython.

Concatenating and Multiplying Tuples

We can concatenate tuples with the + operator, and multiply tuples with the * operator.

The + operator can be used to concatenate two or more tuples together. We can assign the values of two existing tuples to a new tuple:

colors = ('red', 'yellow', 'green', 'purple')
fruits = ('apple', 'banana', 'watermelon', 'grape')

colors_fruits = (colors + fruits)

print(colors_fruits)

The output is as follows:

('red', 'yellow', 'green', 'purple', 'apple', 'banana', 'watermelon', 'grape')

The * operator can be used to multiply tuples. For example, let's multiply the colors tuple by 2 and the fruits tuple by 3, and assign those to new tuples:

multiplied_colors = colors * 2
multiplied_fruites = fruites * 3

print(multiplied_colors)
print(multiplied_fruites)

The output is as follows:

('red', 'yellow', 'green', 'purple', 'red', 'yellow', 'green', 'purple')
('apple', 'banana', 'watermelon', 'grape', 'apple', 'banana', 'watermelon', 'grape', 'apple', 'banana', 'watermelon', 'grape')

We can learn more about Python operator in the Python 3 Operators section.

In fact, the sequence operations used on strings are equally applicable on tuples.

Python Expression Results Description
len((1, 2, 3)) 3 Length
(1, 2, 3) + (4, 5, 6) (1, 2, 3, 4, 5, 6) Concatenation
('Hi!',) * 4 ('Hi!', 'Hi!', 'Hi!', 'Hi!') Repetition
3 in (1, 2, 3) True Membership
for x in (1,2,3) : print (x, end = ' ') 1 2 3 Iteration

In the next chapter we will learn the last collection type in python: dictionary.

0 Comment

temp