Tuples

1. Tuples are ordered and unchangeable (immutable) collections of data. They can be thought of as immutable lists. They are written in round brackets:

Each tuple element may be of a different type (i.e., integers, strings, booleans, etc.). What is more, tuples can contain other tuples or lists (and the other way round).

 

2. You can create an empty tuple like this:

 

3. A one-element tuple may be created as follows:


If you remove the comma, you will tell Python to create a variable, not a tuple:

 

4. You can access tuple elements by indexing them:


 

5. Tuples are immutable, which means you cannot change their elements (you cannot append tuples, or modify, or remove tuple elements). The following snippet will cause an exception:


However, you can delete a tuple as a whole:


 

6. You can loop through a tuple elements (Example 1), check if a specific element is (not)present in a tuple (Example 2), use the len() function to check how many elements there are in a tuple (Example 3), or even join/multiply tuples (Example 4):


 

7. You can also create a tuple using a Python built-in function called tuple(). This is particularly useful when you want to convert a certain iterable (e.g., a list, range, string, etc.) to a tuple:

 

By the same fashion, when you want to convert an iterable to a list, you can use a Python built-in function called list():

 

 

Exercise 1

What happens when you attempt to run the following snippet?

 

The program will print 3 to the screen.

 

Exercise 2

What is the output of the following snippet?

 

The program will print 6 to the screen. The tup tuple elements have been “unpacked” in the a, b, and c variables.

 

Exercise 3

Complete the code to correctly use the count() method to find the number of duplicates of 2 in the following tuple.

Solution:

 

Ex. 4

What is the output of the following code snippet?

 

A TypeError exception

  • Tuples are immutable and do not support item deletion.

 

Ex. 5

Which of the following statements about lists and tuples are false?

(Select two answers)

Tuples have a fixed length, while lists have a variable length

The sort(), insert(), and append() methods belong to both tuples and lists

Lists are indexed while tuples are an unordered set

Tuples are immutable, while lists are mutable collections of data

Correct selection

The sort(), insert(), and append() methods belong to both tuples and lists

Lists are indexed while tuples are an unordered set

  • Both lists and tuples are indexed (with initial index equal to 0).
  • sort(), pop(), and append() are list methods and cannot be used with tuples.

 

Ex. 6

According to the following code snippet, which of the following statements generates an exception?

(Select two answers)

a, b, c, d = tpl

del tpl[3:]

print(tpl[4][0])

print(tpl[2:100])