Tuples in Python

Tuples in Python are similar to lists. In this tutorial, I will be focusing mainly on the differences between lists and tuples. All the examples covered for the list tutorial are applicable to tuples as well.

Tuples are sequences, just like lists. The differences between tuples and lists are, the tuples cannot be changed like lists, because tuples are immutable.

A tuple in python can be defined by placing items inside the parenthesis whereas for lists we use square brackets. Tuple can also contain duplicate items.

t=(1, 2, 1, [1, 2], 'a')

# empty tuple
t=()

How to Create Tuples in Python

To create a tuple with only one item, make sure to add a comma after the item, else Python will not recognize the variable as a tuple.

t=('a')
print(type(t))
t=('a',)
print(type(t))

Accessing tuple elements in Python

Like lists, a tuple can be accessed by

  • Positive index
  • Negative index
  • Range of positive index and negative index
  • for loop(most commonly used method)
    t=(1,2,3,'a','b','c')
    
    # Postive index 
    print(t[1]) 
    
    # Negative index 
    print(t[-4]) 
    
    #Range of positive index 
    print(t[0:4]) 
    
    #Range of negative index 
    print(t[-5:-1])
    
    #for loop
    for i in t:
       print(i)

Changing elements of a tuple in Python

Once a tuple is created, you cannot change its values hence the Tuples are called as unchangeable or immutable.

If you want to change a tuple, then the tuple can be converted into a list for making changes. After making the changes, the list can be converted back to the tuple.

t=(1,2,3)
t.append(4)
l=list(t)
l.append('a')
t1=tuple(l)
print(t1,t)

To join two or more tuples you can use the + operator and store it to a new tuple.

t=(1,2)+('a','b')
print(t)

Deleting a tuple

The del keyword is used to delete the entire tuple

t=(1,2,3)
del t

Other basic tuple operations

len()

len() is used to find the length of the tuple

tuple()

tuple() constructor is used to create a tuple

in operator

To check if the specified item is present in a tuple.

Examples

# len() 
print(len((1,2,3,'a','b','c'))) 

# tuple() 
print(tuple('abc')) 
print(tuple(['bc',1])) 

# in 
t=(1,2,3,'a','b','c') 
print('a' in t) 
print('d' in t)

Conclusion

When tuples in python and lists do the same thing, why we need tuples. The major advantage tuple has over lists are:

  • Constants are faster as variables. Similarly, tuples are faster than lists.
  • The list has append() function. In order for most of the appends to be fast, python will actually create a larger array in memory just in case you append. On the other hand, tuples are immutable. Hence tuples are more explicit with memory, while lists require overhead.

Reference Python Tutorial

Translate »