10+ simple examples to learn python tuple in detail

In this tutorial we will learn about Python tuples data type.

 

What are Python tuples?

  • A tuple is a collection of comma-separated values.
  • It is identical to a list, except it is immutable.
  • When something is immutable, it means that it cannot be altered once declared.
  • Tuples are useful for storing information that you don’t want to change.
  • They’re ordered like lists, so you can iterate through them using an index.
  • Iterating over tuples is much faster than iterating over lists.

 

Comparison between different Python Data Types

Below table shows a summary of the differences between each data types:

Data TypeOrderedIterableUniqueImmutableMutable
ListYesYesNoNoYes
DictionaryNoYesKeys onlyKeys onlyValues only
TupleYesYesNoYesNo
SetNoYesYesNoYes
FrozensetNoYesYesYesNo

 

Python tuples syntax (creating tuple)

A tuple consists of a number of individual values, separated by commas (just like lists). As with lists, a tuple can contain elements of different types. You create a tuple by placing all of the comma-separated values in parentheses, ()

#!/usr/bin/env python3

cars = ('maruti', 'jazz', 'ecosport')
print(type(cars))

Output from this script:

 ~]# python3 tuple-syntax.py
<class 'tuple'>

So here our tuple is placed under parenthesis () which we can check using type(). Although it is not mandatory, you can also create a tuple without using parenthesis

#!/usr/bin/env python3

cars = ('maruti', 'jazz', 'ecosport')
print(type(cars))

Here also the the type of our variable is tuple, output from this script:

~]# python3 tuple-syntax.py
<class 'tuple'>

The output version of a tuple will always be enclosed in parentheses, no matter which method you used to create it. This prevents confusion and allows us to better interpret tuples visually.

 

Access tuple items using indexing

Similar to lists, we can use the index operator [] to access an element in a tuple by using its index. Tuple indices start at zero, just like those of lists.

python tuple
Illustration of Python Index Values

 

Example-1: Using positive index value

As mentioned earlier, the first index of the tuple will start by 0 so to access the first element we use tuple[0]. Here is an example which will make this point more clear:
10+ simple examples to learn python tuple in detail

Output from this script:

 ~]# python3 tuple-index.py
First car:  maruti
Second car:  jazz
Third car:  ecosport

Now here the challenge would be accessing the last item of the tuple for which we have negative indexing value.

 

Example-2: Using negative index value

To access the first item of a tuple we used index as 0, similarly to access the last item of a tuple we will use -1
10+ simple examples to learn python tuple in detail

Output from this script:

 ~]# python3 tuple-index.py
Last car:  ecosport
Second last car:  jazz
Third last car:  maruti

So you can use either the positive or negative index value to access the tuple content.

 

Example-3: Some error scenarios while accessing tuple items

If you try to access an index that is not in the tuple. Python will raise an IndexError, as shown here:

#!/usr/bin/env python3

cars = ('maruti', 'jazz', 'ecosport')

print(cars[4])

Output from this script:

 ~]# python3 tuple-index.py
Traceback (most recent call last):
  File "tuple-index.py", line 5, in 
    print(cars[4])
IndexError: tuple index out of range

Since cars tuple in my example contains only 3 index values, while accessing the 4th value we get IndexError

Next possible error scenario would be if you give a non-integer value with tuple index in which case you will get TypeError. Here in this python script example I am trying to access index value 2 of cars tuple but I have used single quote while providing the index value which will Python will read as string instead of integer.

#!/usr/bin/env python3

cars = ('maruti', 'jazz', 'ecosport')

print(cars['2'])

Output from this script:

~]# python3 tuple-index.py
Traceback (most recent call last):
  File "tuple-index.py", line 5, in 
    print(cars['2'])
TypeError: tuple indices must be integers or slices, not str

As expected, cars['2'] due to the single quote is considered as string which is not allowed with index value hence we get TypeError

 

Access tuple items using slicing

While indexing allows you to access an individual element in a tuple, slicing allows you to access a subset, or a slice, of the tuple.

Syntax to use slicing operator

Slicing uses the slicing operator, :, and the general syntax is as follows:

tupleToSlice[Start index (included):Stop index (excluded):Increment]

All of these parameters are optional, and this is how they work:

  • Start index: The index at which to start the slicing. The element at this index is included in the slice. If this parameter is absent, it is assumed to be zero, and thus, the slicing starts at the beginning of the tuple.
  • Stop index: The index at which to stop slicing. The element at this index is not included in the slice. This means that the last item in this slice will be the one just before the stop index. If this parameter is absent, the slice ends at the very end of the tuple.
  • Increment: This determines how many steps to take in the tuple when creating the slice. If this parameter is absent, it is assumed to be one.

 

Example-1: Create even numbers using tuples with slicing

In this example we will create a range of numbers from 0 to 10 wherein we will print only the even numbers. We had done similar exercise with range() by providing the start, stop and step up value, now we will do something similar but using tuples with slicing.
10+ simple examples to learn python tuple in detail

Output from this script:

~]# python3 tuple-slicing.py
(1, 2, 3, 4, 5, 6, 7, 8, 9)
(2, 4, 6, 8)

Here, we set the start index to 1 (the second element of the tuple) and the increment to 2, so that it skips one element every time.

 

Example-2: Create odd numbers using tuples with slicing

Similarly we can create odd numbers from a range of numbers by slicing the tuple by using the default start index value i.e. 0 and using increment of 2
10+ simple examples to learn python tuple in detail

Output from this script:

~]# python3 tuple-slicing.py
(1, 2, 3, 4, 5, 6, 7, 8, 9)
(1, 3, 5, 7, 9)

Here, we start at index zero (the first element of the tuple) and set the increment to 2, so that it skips one element every time.

 

Example-3: Access tuple items within a defined range

Now we can also use slicing to access the content of tuple within a defined range. In above examples, we concentrated on the increment value, but if we remove increment value from the syntax then we can just provide a start and stop value which will print only the values from the provided range:
10+ simple examples to learn python tuple in detail

Here I would like to print the items between index value 4 and 7, output from this script:

 ~]# python3 tuple-slicing.py
(0, 1, 2, 3, 4, 5, 6, 7, 8, 9)
(4, 5, 6)

Similarly we can also use negative index value which we learned earlier:
10+ simple examples to learn python tuple in detail

In this example we are using negative index value to access the tuple content between last index and 6th last value:

 ~]# python3 tuple-slicing.py
(0, 1, 2, 3, 4, 5, 6, 7, 8, 9)
(4, 5, 6, 7, 8)

 

Adding items to tuples

As I mentioned in the table under comparison of different data types, tuples are immutable or in laymen terms unchangeable which means you cannot modify the content of tuple.

#!/usr/bin/env python3

cars = ('maruti', 'jazz', 'ecosport')
cars[1] = 'kwid'
print(cars)

Here I am trying to modify the content of index value 1 i.e. jazz with kwid, output from this script:

~]# python3 tuple-index.py
Traceback (most recent call last):
  File "tuple-index.py", line 4, in 
    cars[1] = 'kwid'
TypeError: 'tuple' object does not support item assignment

We get TypeError with this operation.

But there is a workaround

We can convert tuple into list, modify the content and re-convert it into tuple. In this python script I convert cars tuple into list and modify the value of the list, then re-convert the list into tuple.
10+ simple examples to learn python tuple in detail

Output from this script:

~]# python3 append-tuple.py
cars_list content:  ['maruti', 'kwid', 'ecosport']
cars content:  ('maruti', 'kwid', 'ecosport')

So now our cars tuple contains new value at index position 1.

 

Example-1: Count occurrences of individual items in tuple

A tuple may also contain duplicate items unlike python sets. So you can use count() to check the number of occurrences of an item in a tuple. This is also the only bound method, as the syntax describes: tuple.count(element).

#!/usr/bin/env python3

cars = ('maruti', 'jazz', 'ecosport', 'maruti')
print('count of maruti element: ', cars.count('maruti'))
print(cars)

Output from this script:

~]# python3 tuple-example-1.py
count of maruti element:  2
('maruti', 'jazz', 'ecosport', 'maruti')

So we had two occurrences of maruti element in our cars tuple.

 

Example-2: Access the smallest item in tuple

We can use min() to get the smallest element in the tuple. Here I have a tuple with a bunch of numbers:

#!/usr/bin/env python3

numbers = (90, 41, 12, 23)
print('smallest element: ', min(numbers))
print(numbers)

Output from the script:

~]# python3 tuple-example-2.py
smallest element:  12
(90, 41, 12, 23)

So our smallest element out of all the items in numbers tuple is 12.

 

Example-3: Access the largest item in tuple

Similar to min() we can use max() to access the largest item in the tuple. We will add one more line to our existing example to get the largest element using max()

#!/usr/bin/env python3

numbers = (90, 41, 12, 23)
print('smallest element: ', min(numbers))
print('largest element: ', max(numbers))
print(numbers)

Output from this script:

~]# python3 tuple-example-3.py
smallest element:  12
largest element:  90

So out of all the items part of our numbers tuple, 90 is the largest while 12 is the smallest.

 

Example-4: Concatenate(join) tuples

We can join tuples just like two strings:
10+ simple examples to learn python tuple in detail

Output from this script:

~]# python3 tuple-example-4.py
(90, 41, 12, 23, 1, 2, 3, 4)

So here we have combined numbers1 and numbers2 into a third tuple variable "total"

 

Example-5: Get the length of a tuple

We can use len() to get the count of all the elements present inside the tuple:

#!/usr/bin/env python3

numbers1 = (90, 41, 12, 23)

print(len(numbers1))

Output from this script:

 ~]# python3 tuple-example-5.py
4

So there are total 4 elements in our tuple.

 

Conclusion

In this tutorial we learned all about Python tutples and different methods to access and modify the content of tuples even though it is immutable. We looked at the various methods that are available for tuple operations, and how to use them in practical applications.

Leave a Comment

Please use shortcodes <pre class=comments>your code</pre> for syntax highlighting when adding code.