Tuples in Python

Tuples are immutable data structures that are used to store a number of data of different types in a single variable. Like lists, tuples are sequences of data stored in a variable. Tuples are one of the four Python built-in Data Structures.
d5

Characteristics

  1. Ordered - Tuple elements are ordered. That is they are stored in a certain order which cannot be changed.
  2. Immutability - Tuples are immutable. That is tuple elements cannot be changed. Elements cannot be added nor deleted in a tuple after it is created.
  3. Duplicacy - Tuples allow duplicate elements to be present in them. This is because they are indexed.
  4. Length of tuples - The len() function can be used to calculate the length of a tuple.

Creation of tuples

A tuple can be created by

  1. typing comma-separated data values against a variable
  2. using the tuple() constructor
  3. simply enclosing a series of comma-separated values within first brackets
  4. single-element tuples can be created by simply adding a comma after the element and enclosing it within a pair of first brackets

Syntax of tuple() constructor,

  <var> = tuple( <any data structure> )

For example,

t1 = 1, "a", 3
t2 = tuple([1, "a", 3])
t3 = (1, "a", 3)
t4 = ("b",)

print(t1)
print(t2)
print(t3)
print(t4)

the outputs are as follows,

(1, 'a', 3)
(1, 'a', 3)
(1, 'a', 3)
('b',)

Accessing tuples

Tuples can be accessed in a way quite similar to Python lists.

  • Indexing - Like lists, tuples are also indexed starting from 0 till one less than the length of the tuple.
t1 = (1, "a", 3, "b", 5)

print(t1[2])

output

3
  • Negative indexing - Python tuples can be accessed using negative indexing too. Negative indexes start from the end of the tuple with the index '-1'.
print(t1[-4])

output

a
  • Range of indexes - A range of tuple elements can be accessed by indicating a range of indexes separated by a colon.
print(t1[1:3])

output

('a', 3)
  • Negative range of indexes - A range of tuple elements can be accessed by indicating a range of negative indexes separated by a colon.
print(t1[-4:-1])

output

('a', 3, 'b')
In both positive as well as a negative range of indexes method of accessing elements of a tuple, keeping any one of the ends of the range empty whilst slicing refers to all the elements present at that end of the tuple.
print(t1[2:])
print(t1[:-3])

output

(3, 'b', 5)
(1, 'a')
  • Membership check using 'in' - To check whether an element is present in a tuple or not, one can use the 'in' keyword.
if "b" in t1:
    print("True")
else:
    print("False")

output

True
  • Iterability of tuples - Tuples are iterable data structures.

Adding/ deleting/ modifying elements of a tuple

  • Tuples are immutable. That is tuples cannot be changed after creation.
  • Neither can elements be added to a tuple, nor deleted.
Though tuple values can be edited, bypassing the immutability factor by first converting the tuple into a list, add/ deleting/ modifying the elements, and then change the list back into a tuple.

An example of the immutability bypass method is as follows,

t1 = (1, "a", 3, "b", 5)

t1 = list(t1)
t1.append("c")
t1.remove(3)
t1 = tuple(t1)

print(t1)

the output becomes,

(1, 'a', 'b', 5, 'c')
Concatenation of Tuples

Tuples can be concatenated together using the '+' sign.

For example,

t1 = (1, "a", 3, "b", 5)
t2 = (5, 6, 8)
t3 = t1 + t2
print(t3)

and the output becomes,

(1, 'a', 3, 'b', 5, 5, 6, 8)

Tuples can be repeated using the '*' operator.

Deleting a tuple

A tuple can be deleted altogether by using the 'del' keyword.

t = (1, 2, 3, 4)
del t
print(t)

it shows,

NameError: name 't' is not defined

Unpacking tuples

The creation of a tuple is also called packing a tuple. Understandably to unpack means to re-allocate the values of the tuple to different variables.

The number of tuple elements should match the number of variables used to unpack them. Otherwise one can use an asterisk (*) against one of the variables to store the rest of the elements as a list.

We can unpack a tuple as follows,

t = (1, 2, 3, 4)
(a, b, c, d) = t
print(a)
print(b)
print(c)
print(d)

output

1
2
3
4

unpacking in form of a list,

(e, *f, g) = t
print(e)
print(f)
print(g)

they show,

1
[2, 3]
4

Tuple methods

The built-in Python tuple functions are as given below,

Methods Description
cmp( <t1> , <t2> ) Compares between the elements of two tuples
index( <val> ) Returns the index of the specified value
max( <t> ) Returns the maximum value in a tuple
min( <t> ) Returns the minimum value in a tuple
count( <val> ) Returns the number of occurrences of a certain value in a tuple

Creating tuples from lists

Lists can be converted into tuples by simply enclosing the list in first brackets along with a single comma alongside.

Lists can also be converted into tuples by using the tuple() constructor by putting the list variable as the argument.

On the other hand tuples can be converted into lists by using the list() constructor by putting the tuple variable as the argument.

Creating tuples from dictionaries

Dictionaries can be converted into a list of tuples by creating tuples from every key-value pair using the items() function. It can also be created by iterating it in list comprehension.

d = {"a": 1, "b": 2, "c": 3}
print(list(d.items()))
print([(u, c) for u,c in dict.items()])

output

[("a", 1), ("b", 2), ("c", 3)]
[("a", 1), ("b", 2), ("c", 3)]

The zip() function can also be used,

print(list(zip(d.keys(), d.values())))

output,

[("a", 1), ("b", 2), ("c", 3)]

The dictionary constructor dict() method can be used to do the reverse. The setdefault() method is also useful.

d = [("a", 1), ("b", 2), ("c", 3)]
print(dict(d))

output

 {"a": 1, "b": 2, "c": 3}
0 results
Comment / Suggestion Section
Point our Mistakes and Post Your Suggestions