Python Fundamentals – Tuples

Python Fundamentals – Tuples

INTRODUCTION

Tuples are very similar to lists, but tuples cannot be changed. That is, a tuple can be viewed as a “constant list”. While lists use square brackets, tuples are written with standard parentheses or no parentheses, and elements are separated with comma as given in the following lists:

a. Syntactically, a tuple is a comma- separated list of values:

b. Although parentheses is not necessary, it is common to enclose tuples in parentheses:

c. To create a tuple with a single element, you have to include a final comma:

DIFFERENCE BETWEEN LIST AND TUPLE

Differences between lists and tuples are as follows:
(a) Lists are enclosed in square brackets [ ], and their elements and size can be changed, while tuples are enclosed in parentheses () and cannot be updated.
(b) Tuples can be thought of as read-only lists. Tuples protect against accidental changes of their contents, whereas Lists will grow and shrink as needed.
(c) One major feature of tuples is that they are immutable like strings, i.e., you can¬not modify tuples. Lists are mutable; individual items or entire slices can be replaced through assignment statements.

TUPLES ARE IMMUTABLE

Like numbers and strings, tuples are immutable which means you cannot update them or change values of tuple elements. A new object has to be created if a different value has to be stored. You can take portions of an existing tuples to create a new tuples as follows:

CREATION, INITIALIZATION AND ACCESSING THE ELEMENTS IN A TUPLE

To create a tuple with zero elements, use only the two parentheses For a tuple with one element, use a trailing comma. For a tuple with two or more elements, use a comma between elements. No ending comma is needed.

Tuple Creation
Creating a tuple is as simple as putting different comma-separated values and option¬ally you can put these comma-separated values between parentheses also. For example:

The empty tuple is written as two parentheses containing nothing:

To write a tuple containing a single value you have to include a comma, even though there is only one value:

A tuple in Python is immutable. An immutable object cannot be changed. Once created it always has the same values. On trying to make an item assignment on a tuple will display the following error:

Tuple Assignment
You can assign all of the elements in a tuple using a single assignment statement. Tuple assignment occurs in parallel rather than in sequence, making it useful for swapping values.
To swap the values of two variables, with conventional assignment statements, we have to use a temporary variable. For example, to swap a and b:

If we have to do this, this becomes cumbersome. Python provides a form of tuple assignment that solves this problem:
a, b = b, a
The left side is a tuple of variables; and the right side is a tuple of values. Each value is assigned to its respective variable. All the expressions on the right side are evaluated before any of the assignments. This feature makes tuple assignment quite versatile.

Accessing Elements in Tuples
To access values in tuple, use the square brackets for slicing along with the index or indices to obtain value available at that index. Like string indices, tuple indices start at 0. Accessed items can be either single elements or in groups, known as slices. Subsets can be taken with the slice operator ( [] and [ : ] ) in the same manner as strings. The slice notation in Python uses a colon. On the left side of the colon, we have the starting index. If no starting index is present, the program uses 0. And on the right side of the colon, we have the ending index. If no ending index is present, the last index possible is used.
For example,

If you want to access value 2013, you can write either tupl[-l] or tupl[3].

Slices are treated as boundaries and the result will contain all the elements between boundaries.

Example 1
Program that uses tuple slices.

Figure 18.1 Program that uses tuple slices

The in operator returns whether a given element is contained in a list or tuple:

TUPLE FUNCTIONS

cmp ()
cmp () function compares elements of both tuples. It checks whether the given tuples are same or not. If both are same, it will return 0, otherwise return 1 or -1. If the first tuple is big, then it will return 1, otherwise return -1.
Syntax:

Example

len()
The method len() returns the number of elements in the tuple.
Syntax:

Example

max() and min()
The max() and min() built-in functions find the largest and smallest elements of a sequence. For strings, the comparison performed is alphabetical, “able” comes before “zero”. So “able” would be less than “zero”. For numbers, the comparison”is numeric, 10 comes before 20. These comparisons are logical.
Syntax:

Example

Example 2
Program that uses max() and min() functions.

Figure 18.2 Program for Example 2

tuple()
It is used to create empty tuple. The empty tuple is written as two parentheses contain¬ing nothing:
Syntax:

Example

SOLVED EXERCISE

Question 1.
What is tuple?

Answer:
Tuples are a sequence of values of any type, and are indexed by integers. They are immutable. Tuples are enclosed in ().

Question 2.
A tuple in Python is immutable. Comment.

Answer:
A tuple in Python is immutable. An immutable object cannot be changed. Once created it always has the same values.

Question 3.
What is the difference between objects and methods?

Answer:
Strings, lists, and tuples are objects, which means that they not only hold values, but have built-in behaviors called methods, that act on the values in the object.

Question 4.
Is an item assignment on a tuple is possible?

Answer:
No, an assignment statement in tuple is not possible.

Question 5.
Why is len() function used with list and tuple?

Answer:
With lists and tuples, len() function returns the number of elements in the sequence:

Question 6.
What is the use of in operator?

Answer:
The in operator returns whether a given element is contained in a list or tuple:

Question 7.
Write short note on tuple assignment.

Answer:
An assignment to all of the elements in a tuple is done using a single assignment statement. Tuple assignment occurs in parallel rather than in sequence, making it useful for swapping values.

Question 8.
How will you create tuple with zero element and 1 element?

Answer:
Zero elements: To create a tuple with zero elements, use only the two parentheses “()”
# Zero element tuple
x = ()

One element: For a tuple with one element, use a trailing comma.
# One-element tuple
y = (“sunday”,)

Question 9.
Compare and contrast tuples and list.

Answer:
Tuples are very similar to lists, but tuples cannot be changed, i.e., no changes in the contents of the tuple is allowed. A tuple can be viewed as a ‘constant list’. While lists employ square brackets, tuples are written with standard parentheses or no paren-theses, and elements are separated by comma in lists.

Question 10.
Can we update tuples?

Answer:
Like numbers and strings, tuples are immutable which means you cannot update them or change values of tuple elements.

Question 11.
Differentiate between following two python statement:
››› t1 = ‘a’,
››› t2 = (‘a’)

Answer:
To create a tuple with a single element, you have to include a final comma:
››› t1 = ‘a’,
››› type(tl)
‹type ‘tuple’›

A value in parentheses is not a tuple:
››› t2 = (‘a’)
››› type(t2)
‹type ‘str’›

Question 12.
What is difference between list and tuple?

Answer:
Lists are enclosed in brackets [ ], and their elements and size can be changed, while tuples are enclosed in parentheses () and cannot be updated. Tuples can be thought of as “read-only” lists.

Question 13.
How will you swap values in Python?

Answer:
Python’s “multiple assignment” will swap values in Python:

Question 14.
Identify the following are mutable or immutable?
lists, numbers, strings, tuples, and dictionaries.

Answer:
Mutable : lists, dictionaries
Immutable : numbers, strings, tuples

Question 15.
Find the output of the following programs:

Answer:
(a) [(1,1,1), (2,4, 8), (3, 9, 27), (4,16, 64)] (b) (10, 20, 30,10, 20, 30)
(c) (10, 20,30,10, 20, 30,10, 20, 30)
(d) Match x = 0
No Match x = 1
Match x = 2
(e) -1
-1
1
0
(f) 126
(42,42,42)

Multiple choice questions

Question 1.
min() returns:
(a) Largest item in the tuple.
(b) Number of items in the tuple.
(c) Its smallest item in the tuple.
(d) None of these

Answer:
(c)

Question 2.
Tuples cannot be:
(a) Added
(b) Multiplied
(c) Sorted
(d) None of the above

Answer:
(c)

Question 3.
In general, the order of items in a dictionary is
(a) Unpredictable
(b) Predictable
(c) Known
(d) None of these

Answer:
(a)

Question 4.
If we need to create a tuple with a single element, we need to include a final:
(a) Comma
(b) Semicolon
(c) Full stop
(d) None of these

Answer:
(a)

Question 5.
Create empty tuple:
(a) T=tuple[] (b) T=tuple()
(c) T=tuple{}
(d) None of these

Answer:
(b)

About the author

James Palmer

Leave a Comment