Learning Python Part-15: Python Tuples

Tuple is an ordered sequence of items just like what we discussed in previous post on Python lists.
The only difference between a Tuple and a list is that tuples are immutable. Tuples once created cannot be modified.

Tuples are used to write-protect data, where you do not want data to be changed in your program. Due to this, Tuples are usually faster than list as it cannot be changed dynamically. 

In order to create a tuple generally use parentheses () where items are separated by commas as shown below.

t = (5,’program’, 1+3j)
print(t[1])                                 ### Output will be (‘program’)
print(t[0:3])                             ### Output will be (5,’program’, 1+3j)

As we mentioned, tuples are immutable, We can use the slicing operator [] to extract items but we cannot change its value as in example below.


t[0] = 10. # Generates error as Tuples are immutable

Elements in tuples, can be of any type i.e. int, float or string. Also a tuple can have any number of elements.

my_tuple = ().                                             # Empty tuple
my_tuple = (1, 2, 3)                                    # Tuple having integers
my_tuple = (1, “Hello”, 3.4)                       # tuple with mixed datatypes
my_tuple = (“mouse”, [8, 4, 6], (1, 2, 3)).  # nested tuple

Tuple Packing and Unpacking:

As we discussed, we generally use parenthesis () to create tuples, however using parentheses is optional. We can create a tuple without using them. This approach of creating tuple is called as Tuple Packing. It is good practice to use () as it makes your code look neat and clean.


my_tuple = 3, 4.6, “dog”


# tuple unpacking is also possible

a, b, c = my_tuple

print(a) # 3
print(b) # 4.6
print(c) # dog


Access Tuple Elements:


There are various ways in which we can access the elements of a tuple as discussed below.


Indexing:

  • Uses the index operator [] to access an item in a tuple where the index starts from 0.
  • The index must be an integer; so we cannot use float or other types. This will result in TypeError.
  • Nested tuples are accessed using nested indexing

t = (‘p’,’y’,’t’,’h’,’o’,’n’)
print(t[1])                                               # Output: ‘y’

t = (“cat”, [8, 4, 6], (1, 2, 3))
print(n_tuple[1][1])                               # Output: 4

Negative Indexing:
  • The index of -1 refers to the last item, -2 to the second last item and so on.

t = (‘p’,’y’,’t’,’h’,’o’,’n’)

print(t[-6])                          # Output: ‘p’


Slicing:

  • We can access a range of items in a tuple by using the slicing operator – colon “:”.

t = (‘p’,’y’,’t’,’h’,’o’,’n’)

print(t[1:4])
print(t[:-6])
print(t[5:])
print(t[:])


# Output:

(‘y’, ‘t’, ‘h’)
()
(‘n’,)
(‘p’, ‘y’, ‘t’, ‘h’, ‘o’, ‘n’)


Changing a Tuple:

  • As we discussed earlier, unlike lists, tuples are immutable. Hence the elements inside tuple cannot be changed once it has been assigned. 
  • However, if the element is itself a mutable datatype like list, its nested items can be changed.
  • We can also assign a tuple to different values (reassignment).

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


print(t)                            # Output: # TypeError: ‘tuple’ object does not support item assignment

t[3][0] = 9

print(t)                            #Output: t = (4, 2, 3, [9, 5]). 


Here we were able to change as we actually changed a list element inside tuple
  • We can use + operator to combine two tuples. This is also called concatenation.
  • We can also repeat the elements in a tuple for a given number of times using the *operator.

print((1, 2, 3) + (4, 5, 6))

print((“Repeat”,) * 3)


Deleting a Tuple:

  • As discussed earlier in this post, we cannot change the elements in a tuple. 
  • That also means we cannot delete or remove items from a tuple.
  • However,  deleting a tuple entirely is possible using the keyword del.


t = (‘p’, ‘y’, ‘t’, ‘h’, ‘o’, ‘n’)

del t


Tuple Methods:


  • Methods that add items or remove items are not available with tuple. 
  • Only the following two methods are available.


  • Some examples of Python tuple methods:


t = (‘p’, ‘y’, ‘t’, ‘h’, ‘o’, ‘n’)

print(t.count(‘p’)) 


 # Output: 1

print(t.index(‘h’)) 

 # Output: 3

Other Tuple Operations:

  • Tuple Membership Test:
    • We can test if an item exists in a tuple or not, using the keyword in.

t = (‘p’, ‘y’, ‘t’, ‘h’, ‘o’, ‘n’)

print(‘o’ in t)

  • Iterating Through a Tuple:
    • Using a for loop we can iterate through each item in a tuple.
for name in (‘Python’,’Kid’):
      print(“Hello”,name)

Advantages of Tuple over List:

  • We generally use tuple for heterogeneous (different) datatypes and list for homogeneous (similar) datatypes.
  • Since tuples are immutable, iterating through tuple is faster than with list. So there is a slight performance boost.
  • Tuples that contain immutable elements can be used as a key for a dictionary. With lists, this is not possible.
  • If you have data that doesn’t change, implementing it as tuple will guarantee that it remains write-protected.

Leave a Reply