Learning Management Platform for Written Tutorial Series.

Python 3 Tuples - With working examples

Python 3 Tuples - With working examples

Python Tuples

Tuples in python are similar to lists except they are read-only. That means once you have defined a tuple, you cannot add more items to it or remove the existing items. They are written in stone :). Unlike lists, tuples are defined using brackets. In this lesson, we will show you how to work with tuples in python.

Topics to be covered

In this lesson, we will cover the following topics.

  • How to create a tuple
  • Accessing items in a tuple
  • Tuple unpacking
  • Tuple methods

How to create a tuple

Let's now look at how you can create a tuple in python.

attributes = ('id','name','username','email','password')

print(type(attributes))

print(attributes)

HERE,

  • attributes = ('id','name','username','email','password') defines a tuple variable attributes
  • print(type(attributes)) prints the data type of the variable attributes
  • print(attributes) prints the items that are in the tuple

Executing the above code produces the following results.

<class 'tuple'>
('id', 'name', 'username', 'email', 'password')

In our definition of tuples, we compared them to lists but they are read-only as opposed to lists. Let's attempt to add an item at index 3 of our tuple.

attributes = ('id','name','username','email','password')

attributes[3] = 'created_at'

HERE,

  • attributes[3] = 'created_at' attempts to assign a new item to the tuple at index 3

Executing the above code produces the following error

Traceback (most recent call last):
  File "tupo.py", line 3, in <module>
    attributes[3] = 'created_at'
TypeError: 'tuple' object does not support item assignment

This is because lists are not mutable. In other words, once defined, we cannot change them.

But let's suppose you are a stubborn programmer and insist on changing the list, you can do a work around like so.

attributes = ('id','name','username','email','password')

attr = list(attributes)

attr[3] = 'created_at'

attributes = tuple(attr)

print(type(attributes))

print(attributes)

HERE,

  • attributes = ('id','name','username','email','password') defines a tuple attributes
  • attr = list(attributes) creates a list variable from our tuple using the list function
  • attr[3] = 'created_at' assigns a new item to our new list attr at index3
  • attributes = tuple(attr) overwrites our original tuple definition to the new one that contains the new item that we added to it.
  • print(type(attributes)) prints the data type of our variable attributes
  • print(attributes) prints the contents of the variable attributes

Executing the above code produces the following results.

<class 'tuple'>
('id', 'name', 'username', 'created_at', 'password')

The above example is meant as a work around of changing tuples for the sake of learning and not how you should go about changing tuples. If you want something that you can modify then use a list.

Accessing items in a tuple

Items in a tuple are index from 0 to the total number of items minus one. For example, if we have a tuple that has 4 items in it, then the last index is 4 - 1 which gives us 3. Trying to access an index that does not exist raises an exception.

Let's say we want to print the second item in our tuple, we can do it like so

attributes = ('id','name','username','email','password')

print(f'the second item is {attributes[1]}')

HERE,

  • attributes[1] extracts the second item from the list. Remember the index formula is position - so the index for the second item is given by 2 - 1 which is 1

Executing the above code produces the following results

the second item is name

Let's now try to access an item with an index that does not exists

attributes = ('id','name','username','email','password')

print(f'the second item is {attributes[9]}')

HERE,

  • attributes[9] attempts to access the 10th index in our tuple.

Executing the above code produces the following error

Traceback (most recent call last):
  File "tupo.py", line 3, in <module>
    print(f'the second item is {attributes[9]}')
IndexError: tuple index out of range

We can also use the in operator to check if an item exists in a list.

attributes = ('id','name','username','email','password')

print('created_at' in attributes)

HERE,

  • 'created_at' in attributes checks to see if the attribute is in the list. If it is, then True is returned otherwise we return False

Executing the above code produces the following result

False

This is because our tuple does not contain the item created_at

If we want to print all the items in a tuple, then we can use a for loop like so

attributes = ('id','name','username','email','password')

for attribute in attributes:
    print(attribute)

The above code produces the following results.

id
name
username
email
password

Tuple unpacking

Tuple unpacking is a feature that allows us to assign the value of a tuple of the right hand side of the expression to the items in a tuple on the left hand side. The tuples on the left hand side then become variables that we can use. Let's get practical and work with an example.

values = ('1','Natasha','katie','amanda@example.com')

(id,name,username,email) = values

print('user details\n')
print(f'id: {id}')
print(f'name: {name}')
print(f'username: {username}')
print(f'email: {email}')

HERE,

  • values = ('1','Natasha','katie','amanda@example.com') defines a tuple that contains user details
  • (id,name,username,email) = values unpacks the first item to id, the second to name and so on and so fourth.
  • print('user details\n') print a heading in the terminal
  • print(f'id: {id}') prints the value of the variable id, the same explanation applies to the other variables

Executing the above code produces the following results.

user details

id: 1
name: Natasha
username: katie
email: amanda@example.com

Tuple methods

Just like lists, we can do some magic tricks on our tuples.

How to get the number of items in a tuple

We can do it like so

values = ('1','Natasha','katie','amanda@example.com')

print(len(values))

HERE,

  • len(values) calls the len function and passes in our tuple as an argument

Executing the above code produces the following results

4

How to sort a tuple in python

In this example, we will create a tuple then sort it in ascending order

letters = ('alef','bet','gimel','dalet','he','vav','zayin','chet','tet','yod','kaf')

print('the original tuple is ')
print(letters)
print('the sorted tuple is')
letters = tuple(sorted(letters)) 
print(letters)

HERE,

  • letters = tuple(sorted(letters)) the sorted function accepts the tuple as a parameter then returns a sorted list. We are using the tuple function to convert the sorted list back into a tuple then overwriting the original tuple.

Executing the above code produces the following results.

the original tuple is
('alef', 'bet', 'gimel', 'dalet', 'he', 'vav', 'zayin', 'chet', 'tet', 'yod', 'kaf')
the sorted tuple is
('alef', 'bet', 'chet', 'dalet', 'gimel', 'he', 'kaf', 'tet', 'vav', 'yod', 'zayin')

Summary

A tuple is a collection of items that cannot be modified after it has been created. The items in the tuple are accessed using index numbers. A tuple is an objected so it comes with built-in methods that we can call to do more without writin custom code for the specific task that the method does. A for loop is used to iterate through a tuple.

What next?

If you enjoyed this lesson then show us your appreciation by creating a free accounts on our site. As always we appreciate your comments down below.


...