Python Tuple (With Examples)

Python tuple is a “collection of objects separated by commas.” A tuple is similar to a Python list in indexing, nested objects, and repetition. Still, the main difference between both is Python tuple is immutable, unlike the Python list, which is mutable.

How to Create a Tuple in Python

To create a tuple in Python, “place all the elements inside the parentheses (), separated by a comma”. The parentheses are optional but are good practice to write them. A tuple can have any number of items, and they may be of different types.

deserts = ('oreo', 1, True, ['Android', 'iOS'], 'pie')

print(deserts)

Let us write a tuple without parentheses.

deserts = 'oreo', 1, True, ['Android', 'iOS'], 'pie'

print(deserts)

How to access tuple elements in Python

To access tuple elements in Python, refer to the index number inside square brackets.

deserts = ('oreo', 1, True, ['Android', 'iOS'], 'pie')

print(deserts[3])

Output

Python Tuple Example Tutorial | Complete Introduction On Python Tuples

How to loop through a Tuple in Python

To loop through a tuple in Python, you can use the “for loop”. A for loop is used for iterating over a sequence. The for loop does not require an indexing variable to be set beforehand.

deserts = ('oreo', 'nougat', 'jellybean', 'pie')

for item in deserts:
  print(item)

Output

Complete Introduction On Python Tuples

Modifying tuple values

Let’s try to change the values in a tuple and see the result.

Example

deserts = ('oreo', 'nougat', 'jellybean', 'pie')

deserts[1] = 'kitkat'

print(deserts)

I am using Visual Studio Code and have installed a Python extension called pylint. That is why my editor throws me an error saying that ‘deserts’ does not support item assignments. Unfortunately, that means we can not modify it. But still, let us run the file and see the output in the console.

Try To Change Tuple Values in Python

Python tuple length

To find a length of a tuple in Python, you can use the “len()” function. The len() method returns how many elements a tuple has.

deserts = ('oreo', 'nougat', 'jellybean', 'pie')

print(len(deserts))

OutputTuple Length in Python

How to remove an element in Tuple

A tuple is unchangeable, so we can’t remove single or multiple elements but can delete the entire tuple.

deserts = ('oreo', 'nougat', 'jellybean', 'pie')

del deserts

print(deserts)

We have used the del keyword to delete the entire tuple. So the above code’s output will get an error because the tuple is already removed. So there is nothing to print because the compiler does not find any deserts tuple. So it throws an error.

Remove Items in Tuple

Python tuple methods

Name Definition
Python tuple index() It returns the first occurrence of the given element from the tuple.
Python tuple count() It returns the number of times the specified element appears in the tuple.

That’s it.

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.