Python Tuple

Python tuple is a list of immutable objects with heterogeneous data. Tuples are enclosed in brackets () with items comma separated.

How to create a tuple in Python?

Tuple in Python is created using small brackets () with the items in the tuple be separated by a comma (,).  A tuple can have any number of items and can be of different data types. To have an idea of python data types, please refer to this tutorial:- Python Datatypes.

Let’s explore some of the examples of the tuple in the following example:-

tuple = ( 'abcd', 786 , 2.23, 'john', 70.2  )
list = [ 'abcd', 786 , 2.23, 'john', 70.2  ]
tuple[2] = 1000    # Invalid syntax with tuple
list[2] = 1000     # Valid syntax with list
  • An empty tuple can be written as tuple = ()
  • The tuple having a single value must include a comma as tuple = (2,)
  • No Enclosing Delimiters can be used for creating a tuple
    tuple = ‘a’, 123, 2.4, ‘John’

How to access elements in a tuple in Python?

We can use a slice operator [] and [:] to get items in the tuple. The concatenation operation can be done using plus (+) sign and asterisk(*) serves as the repetition operator. We can use two types of indexing to get items viz. positive indexing and negative indexing. Positive indexing allows to index items from 0 to n where negative index gives access from backward, where -1 is the last item.

Below is an example of tuple with simple operations:-

tuple = ('abcd', 786 , 2.23, 'john', 70.2)
print(tuple)          #Prints complete tuple
print(tuple[0])       #Prints first element of the tuple
print(tuple[1:3])     #Prints elements starting from 2nd till 3rd
print(tuple[2:])      #Prints elements starting from 3rd element
print(tuple[-1])      #Prints last element

Output:-

(‘abcd’, 786, 2.23, ‘john’, 70.2)
abcd
(786, 2.23)
(2.23, ‘john’, 70.2)
70.2

How to change or add elements to a tuple in Python?

Since tuples are immutable data types, you cannot add, edit or delete any item in a tuple.

colors = ('red', 'green', 'blue')
print("Current tuple", colors)
colors = ('black', 'gray', 'blue')
print("Updated new color", colors)

colors[1] = 'black'
It gives the following output:-
Current tuple (‘red’, ‘green’, ‘blue’)
Updated new color (‘black’, ‘gray’, ‘blue’)
Traceback (most recent call last):
File “testing.py”, line 6, in <module>
colors[1] = ‘black’
TypeError: ‘tuple’ object does not support item assignment
Here you can see that we can reassign tuple but cannot modify the index element.

 How to delete or remove elements from a Tuple in Python?

As tuples are immutable, we cannot delete individual items in tuple, but the tuple can be deleted as a whole using del function.

How to iterate over a Tuple in Python?

A tuple can be iterated using for loop. Let us see the following example:-

colors = ('red', 'green', 'blue', 'gray', 'black')
for color in colors:
    print(color)
red
green
blue
gray
black

What are Python Tuple Operations?

OperatorDescription
+Concatenation of two tuples
*Repetition operator, to repeat tuple in multiple times
inMembership operator to check if an item exists in a tuple
not inMembership operator to check if an item does not exist in a tuple

What are Python Tuple Built-in functions?

Python provides the following built-in functions which can be used with the tuples..

FunctionDescription
cmp(tuple1, tuple2)Compares the elements of left and right tuple
len(tuple)Calculate the length of the tuple
max(tuple)Returns the maximum element of the tuple
min(tuple)Returns the minimum element of the tuple
tuple(seq)Converts any sequence to the tuple
sum()Returns the sum of all elements in the tuple
sorted()
Returns the new sorted tuple
enumerate()Returns an enumerated object
all()Returns true if all elements in the tuple are True
any()Returns true if any element in tuple is True

What are Python Tuple built-in methods?

Python provides just two methods that can help you perform the various operations in a tuple. Following are some of the built-in tuple methods:-

MethodDescription
count()Returns the count of the number of items passed as an argument
index() Returns the index of the first matched item

 

SHARE Python Tuple

You may also like...

Leave a Reply

Your email address will not be published.

Share