Skip to content
Home » TUPLES

TUPLES

INTRODUCTION

The python tuples are sequences that are used to store a tuple of values of any type. Tuples are immutable i.e., you cannot change the values of elements of a tuple in Python. Python will create a fresh tuple when you make changes to an element in a tuple.

In this session we shall be learning about creating and accessing tuples, various tuple operations and tuple manipulations through some built in functions.

CREATING AND ACCESSING TUPLES

A tuple is a standard data type of Python that can store a sequence of values belonging to any type. The tuples are depicted through parentheses ().

() #tuple with no element

(1,2,3) #tuple of integers

(1,3.4,5) #tuple of numbers

(‘a’,’b’,’c’) #tuple of characters

(‘one’,’two’) #tuple of strings

(1,’a’,4.5,’one’) #tuple of mixed values

Creating tuples

To create a tuple you can write in the form given below:

t=()

t=(value,…..)

This construct is known as tuple display construct.

1.Empty tuple:

The empty tuple is (). It is the tuple equivalent to 0 or “ ”. You can also create empty tuple as:

t=tuple()

It will generate an empty tuple and name that tuple as t.

2.Single element tuple:

Making a tuple with a single element is tricky because if you just give a single element in round bracket, Python considers it a value only,e.g.,

>>>t=(1)

>>>t

1

To construct a tuple with one element just add a comma after the single element as shown below:

>>>t=3,

>>>t

(3,)

>>>t=(4,)

>>>t

(4,)

3.Long tuples:

If a tuple contains many elements, then to enter such long tuples, you can split it across several lines, as given below:     sqrs=(1,4,9,16,25,36,49,72,81,100,144,169,192,225,256,289,324,361,400,441,484,529,576,625)

Notice the opening parentheses and closing parentheses appearing just at the beginning and the end of the tuple.

4.Nested tuple:

If a tuple contains an element which is a tuple itself then it is called nested tuple e.g., following is a nested tuple:

t1=(1,2,(3,4))

The tuple t1 has three elements in it: 1,2 and (3,4). The third element of tuple t1 is a tuple itself, hence, t1 is a nested tuple.

Creating tuples from existing sequences

You can also use the built in tuple type object (tuple()) to create tuples from sequences as per the syntax given below:

t=tuple(sequence)

Where <sequence> can be any kind of sequence object including strings, lists and tuples.

Consider the following examples:

>>>t1=tuple(‘hello’)

>>>t1

(‘h’,’e’,’l’,’l’,’o’)

l=[‘w’,’e’,’r’,’t’,’y’]

t2=tuple(l)

print(t2)

Output:

(‘w’, ‘e’, ‘r’, ‘t’, ‘y’)

 You can use this method of creating tuples of single characters or single digits via keyboard input. Consider the example:

t1=tuple(input(“Enter tuple elements:”))

print(t1)

Output:

Enter tuple elements:123456789

(‘1’, ‘2’, ‘3’, ‘4’, ‘5’, ‘6’, ‘7’, ‘8’, ‘9’)

see , with tuple() around input(), even if you do not put parenthesis, it will create a tuple using individual characters as elements. But most commonly used method to input tuples is eval(input()) as shown below:

tuple=eval(input(“Enter tuple to be added:”))

print(“Tuple you entered:”,tuple)

Output:

Enter tuple to be added:(2,’hi’,17,16,4.5)

Tuple you entered: (2, ‘hi’, 17, 16, 4.5)

If you are inputting a tuple with eval(), then make sure to enclose the tuple elements in parenthesis.

Accessing elements

Tuples are immutable sequences having a progression of elements. Thus, other than editing items, you can do all that you can do with lists. Thus like this, you can access individual elements.

Similarity with lists

Tuples are very much similar to lists except for the mutability. In other words, Tuples are immutable counter-parts of lists. Thus, like lists, tuple elements are also indexed, i.e., forward indexing as 0,1,2,3,……..and backward indexing as -1,-2,-3…

Thus, you can access the tuple elements just like you access a list’s or a string’s elements e.g., tuple[i] will give you an element at ith index; tuple[a:b] will give you elements between indexes a to b-1 and so on.

Put in other words, tuples are similar to lists in following ways:

  • Length: function len(t) returns the number of items in the tuple t.
  • Indexing and slicing:
  • T[i] returns the item at index i
  • T[i:j] returns a new tuple, containing the objects between i and j excluding index j.
  • T[i:j:n] returns a new tuple, containing every nth element from index i to j, excluding index j.
  • Membership operators: both ‘in’ and ‘not in’ operators work on Tuples just like they work for other sequences. That is, in tells if an element is present in the tuple or not and not in does the opposite.
  • Concatenation and replication operators + and *:the + operator add one tuple to the end of the other. The * operator repeats a tuple.

Accessing individual elements 

Consider the following examples:

>>>vowels=(‘a’,’e’,’i’,’o’,’u’)

>>>vowels[0]

‘a’

>>>vowels[-2]

‘o’

Difference from lists

Although tuples are similar to lists in many ways, yet there is an important difference in mutuality of the two. Tuples are not mutable, while lists are. You cannot change individual elements of a tuple in place, but lists allow you to do so.

Immutable types with mutable elements

So now it is clear to you that immutable type like tuples cannot have item assignment, i.e.,you cannot change its elements. But what if a tuple contains mutable elements e.g., a list at its element? In that case, would you be able to modify the list elements of the tuple or not? Well, read on.

If a tuple contains mutable elements such as lists or dictionaries, the tuple’s elements once assigned will not change, but its individual mutable elements can change their own elements’ value.

To understand, go through the following example.

Say you have a tuple which stores two elements of list types:

>>>numbers=([1,2,3],[4,5,6])

Internally, the above tuple will store its list elements

Now if you try to modify the elements of tuple numbers by giving a statement like:

>>>numbers[1]=[1,2,0]

TypeError                                 Traceback (most recent call last)

Cell In[1], line 2

      1 numbers=([1,2,3],[4,5,6])

—-> 2 numbers[1]=[1,2,0]

TypeError: ‘tuple’ object does not support item assignment

 This is because the above is trying to change the first element of tuple numbers but as tuples are immutable, no matter what, the tuple numbers will always keep referring to its first list element stored address. That is the address of the first list element that will always remain the same.

But if you give a statement like

>>>numbers[0][2]=0

It will give no error. This is because the tuple numbers’ elements’ memory addresses are not changed; the tuple numbers are still referring to the same Python list objects at the stored address. However, the list stored at addresses is now having different elements, which is allowed as lists are mutable and their elements can change.

Now if you print the numbers tuples, it will give you result as:

>>>print(numbers)

([1,2,0],[4,5,6]

Traversing a tuple

Traversal of a sequence means accessing and processing each element of it. Thus traversing a tuple also means the same and same is the tool for it, i.e., the Python loops. The for loop makes it easy to traverse or loop over the items in a tuple, as per the following syntax:

for <item> in <Tuple>:

process each item here 

For example, the following loop shows each item of  tuple t in separate lines:

t=('P','y','t','h','o','n')
for a in range(len(t)):
    print(t[a])

Output:

P

y

t

h

o

n

TUPLE OPERATIONS

Joining tuples:

Joining two tuples is very easy just like you perform addition, literally ;). The + operator, the concatenation operator, when used with two tuples, joins two tuples.

Consider the example given below:

>>>t1=(10,12,13)

>>>t2=(6,7,8)

>>>t1+t2

 (10, 12, 13, 6, 7, 8)

The + operator when used with tuples requires that both the operands must be of tuple types. You cannot add a number or any other value to a tuple. For example, following expressions will raise into error:

Tuple+number

Tuple+complex number

Tuple+string

Tuple+list

Repeating or replicating tuples

Like strings and lists, you can use * operator to replicate a tuple specified number of times, e.g., if t1 is (1,3,5), then

>>>t1*3

(1,3,5,1,3,5,13,5)

Slicing the tuples

Tuple slices, like list slices or string slices are the sub parts of the tuple extracted out. You can use indexes of tuple elements to create tuple slices as per the following syntax:

    seq=t[start:stop]

The above statement will create a tuple slice namely seq having elements of the tuple t on indexes start, start+1,start+2…….,stop-1. Recall that index on the last limit is not included in the tuple slice. The tuple slice is a tuple in itself that is you can perform all operations on it just like you perform on tuples. Consider the following example:

tpl=(10,12,14,20,22,24,30,32,34)
seq=tpl[3:-3]
print(seq)

Output:

(20, 22, 24)

For normal indexing, if the resulting index is outside the tuple, Python raises an index error exception. Slices are treated as boundaries instead, and the result will simply contain all items between the boundaries. For the start and stop given beyond tuple limits in a tuple slice, Python simply returns the elements that fall between specified boundaries, if any.

For example, consider the following examples:

tpl=(10,12,14,20,22,24,30,32,34)
print(tpl[3:30])
print(tpl[-15:7])

Output:

(20, 22, 24, 30, 32, 34)

(10, 12, 14, 20, 22, 24, 30)

Tuples also support slice steps too. That is, if you want to extract, not consecutive but every other element of the tuple, there is a way out-the slice steps. The slice steps are used as per the following syntax:

seq=t[start:stop:step]

Consider some examples to understand this:

print(tpl)
print(tpl[0:10:2])
print(tpl[::2])
print(tpl[::-1])

Output:

(10, 12, 14, 20, 22, 24, 30, 32, 34)

(10, 14, 22, 30, 34)

(10, 14, 22, 30, 34)

(34, 32, 30, 24, 22, 20, 14, 12, 10)

UNPACKING A TUPLE

when we create a tuple,we normally assign values to it. this is called “packing” a tuple

Unpacking a tuple:

EXAMPLE:

fruits = ("apple", "banana", "cherry")
(green, yellow, red) = fruits
print(green)
print(yellow)
print(red)

OUTPUT:

apple

banana

cherry

Note: The number of variables must match the number of values in the tuple, if not, you must use an asterisk to collect the remaining values as a list.

USING ASTERISK*

If the number of variables is less than the number of values we can add an * to the variable name and the values will be assigned to the variable as a list

EXAMPLE:

fruits = ("apple", "banana", "cherry", "strawberry", "raspberry")
(green, yellow, *red) = fruits
print(green)
print(yellow)
print(red)

OUTPUT:

apple

banana

[‘cherry’, ‘strawberry’, ‘raspberry’]

METHODS IN TUPLES

**tup.count(item)–>Returns the number of times a specified value occurs in a tuple

EXAMPLE:

t=(2,4,2,5,3,6,2,7,8,3,9,2,4,10)
print(t.count(2))

OUTPUT:

2

**tup.index(item)–>Searches the tuple for a specified value and returns the position of where it was found

EXAMPLE:

t=('a','b','c','a','d','e')
print(t.index('c'))

OUTPUT:

2

**sorted(seq,reverse=True/False):takes the name of the tuple as an arguement and returns a new list

EXAMPLE 1:

val=(15,17,16,11,19)
sval=sorted(val)
print(sval)

OUTPUT:

[11, 15, 16, 17, 19]

EXAMPLE 2:

val=(15,17,16,11,19)
sval=sorted(val,reverse=True)
print(sval)

OUTPUT:

[19, 17, 16, 15, 11]