What is Python Tuple – Creating, Functions, Methods, Operations

Free Python courses with 57 real-time projects - Learn Python

In this Python Tuple tutorial, we will rather take a deeper look at Python tuple. First, let’s look at what a Python tuple is and then we will discuss how to create, access, slice, delete tuple in Python.

Moreover, we will learn the functions, methods, and operations of Python tuples.

Python provides a range of constructs to deal with items. These include python lists, dictionaries, sets, tuples, and many more. It also supports in-built functions and methods that we can apply on these constructs.

So, let’s start the Python tuple Tutorial.

What is Python Tuple - Creating, Functions, Methods, Operations

What is Python Tuple – Creating, Functions, Methods, Operations

What is Python Tuple?

Python Tuples are like a list. It can hold a sequence of items. The difference is that it is immutable. Let’s learn the syntax to create a tuple in Python.

How to Create a Python Tuple?

To declare a Python tuple, you must type a list of items separated by commas, inside parentheses. Then assign it to a variable.

>>> percentages=(90,95,89)

You should use a tuple when you don’t want to change just an item in future.

1. Python Tuples Packing

You can also create a Python tuple without parentheses. This is called tuple packing.

>>> b= 1, 2.0, 'three'

2. Python Tuples Unpacking

Python tuple unpacking is when you assign values from a tuple to a sequence of variables in python.

>>> percentages=(99,95,90,89,93,96)
>>> a,b,c,d,e,f=percentages
>>> c

Output

90

You can do the same to a list.

3. Creating a tuple with a single item

Until now, we have seen how easy it is to declare a Python tuple. But when you do so with just one element, it may create some problems. Let’s take a look at it.

>>> a=(1)
>>> type(a)

Output

<class ‘int’>

Wasn’t the type() method supposed to return class ‘tuple’?

To get around this, we add a comma after the item.

>>> a=(1,)
>>> type(a)

Output

<class ‘tuple’>

Problem solved. And as we saw in tuple packing, we can skip the parentheses here.

>>> a=1,
>>> type(a)

Output

<class ‘tuple’>

Also, like a list, a Python tuple may contain items of different types.

>>> a=(1,2.0,'three')

How to Access Python Tuple?

1. Accessing the entire tuple

To access a tuple in python, just type its name.

>>> percentages

Output

(90, 95, 89)

Or, pass it to the print statement.

>>> print(percentages)

Output

(90, 95, 89)

2. Accessing a single item

To get a single item from a Python tuple, use its index in square brackets. Indexing begins at 0.

>>> percentages[1]

Output

95

Slicing a Tuple in Python

If you want a part(slice) of a tuple in Python, use the slicing operator [].

>>> percentages=(99,95,90,89,93,96)

1. Positive Indices

When using positive indices, we traverse the list from the left.

>>> percentages[2:4]

Output

(90, 89)

This prints out items from index 2 to index 3 (4-1) (items third to fourth).

>>> percentages[:4]

Output

(99, 95, 90, 89)

This prints out items from the beginning to the item at index 3.

>>> percentages[4:]

Output

(93, 96)

This prints out items from index 4 to the end of the list.

>>> percentages[2:2]

Output

()

However, this returns an empty Python tuple.

2. Negative indexing

Now, let’s look at negative indexing. Unlike positive indexing, it begins traversing from the right.

>>> percentages[:-2]

Output

(99, 95, 90, 89)

This prints out the items from the tuple’s beginning to two items from the end.

>>> percentages[-2:]

Output

(93, 96)

This prints out items from two items from the end to the end.

>>> percentages[2:-2]

Output

(90, 89)

This prints out items from index 2 to two items from the end.

>>> percentages[-2:2]

Output

()

This last piece of code, however, returns an empty tuple. This is because the

start(-2) is behind the end(2) in this case.

Lastly, when you provide no indices, it prints the whole Python tuple.

>>> percentages[:]

Output

(99, 95, 90, 89, 93, 96)

Deleting a Python Tuple

As we discussed above, a Python tuple is immutable. This also means that you can’t delete just a part of it. You must delete an entire tuple, if you may.

>>> del percentages[4]

Output

Traceback (most recent call last):File “<pyshell#19>”, line 1, in <module>

del percentages[4]

TypeError: ‘tuple’ object doesn’t support item deletion

So, deleting a single element didn’t work. Let’s try deleting a slice.

>>> del percentages[2:4]

Output

Traceback (most recent call last):File “<pyshell#20>”, line 1, in <module>del percentages[2:4]

TypeError: ‘tuple’ object does not support item deletion

As you can see, that didn’t work either. Now, let’s try deleting the entire tuple.

>>> del percentages
>>> percentages

Output

Traceback (most recent call last):File “<pyshell#40>”, line 1, in <module>

percentages

NameError: name ‘percentages’ is not defined

We see that the Python tuple has successfully been deleted.

Reassigning Tuples in Python

As we discussed, a Python tuple is immutable. So let’s try changing a value. But before that, let’s take a new tuple with a list as an item in it.

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

Now, let’s try changing the list [4,5]. Its index is 3.

>>> my_tuple[3]=6

Output

Traceback (most recent call last):File “<pyshell#43>”, line 1, in <module>

my_tuple[3]=6

TypeError: ‘tuple’ object does not support item assignment

See, that failed. Now how about changing an element from the same list]?

>>> my_tuple[3][0]=6
>>> my_tuple

Output

(1, 2, 3, [6, 5])

This worked without a flaw. So we can see that while tuples are immutable, a mutable item that it holds may be reassigned.

Python Tuple Functions

A lot of functions that work on lists work on tuples too. A function applies on a construct and returns a result. It does not modify the construct. Let’s see what we can do.

 Python Tuple Functions

Python Tuple Tutorial – Python Tuple Functions

1. len()

Like a list, a Python tuple is of a certain length. The len() function returns its length.

>>> my_tuple

Output

(1, 2, 3, [6, 5])
>>> len(my_tuple)

Output

4

It returned 4, not 5, because the list counts as 1.

2. max()

It returns the item from the tuple with the highest value.

We can’t apply this function on the tuple my_tuple, because ints cannot be compared to a list. So let’s take yet another tuple in Python.

>>> a=(3,1,2,5,4,6)
>>> max(a)

Output

6

Let’s try that on strings.

>>> max(('Hi','hi','Hello'))

Output

‘hi’

‘hi’ is the greatest out of these, because h has the highest ASCII value among h and H.

But you can’t compare an int and a string.

>>> max(('Hi',9))

Output

Traceback (most recent call last):File “<pyshell#59>”, line 1, in <module>

max((‘Hi’,9))

TypeError: ‘>’ not supported between instances of ‘int’ and ‘str’

3. min()

Like the max() function, the min() returns the item with the lowest values.

>>> min(a)

Output

1

As you can see, 1 is the smallest item in this Python tuple.

4. sum()

This function returns the arithmetic sum of all the items in the tuple.

>>> sum(a)

Output

21

However, you can’t apply this function on a tuple with strings.

>>> sum(('1','2','3'))

Output

Traceback (most recent call last):File “<pyshell#57>”, line 1, in <module>

sum((‘1′,’2′,’3’))

TypeError: unsupported operand type(s) for +: ‘int’ and ‘str’

5. any()

If even one item in the tuple has a Boolean value of True, then this function returns True. Otherwise, it returns False.

>>> any(('','0',''))

Output

True

The string ‘0’ does have a Boolean value of True. If it was rather the integer 0, it would’ve returned False.

>>> any(('',0,''))

Output

False

6. all()

Unlike any(), all() returns True only if all items have a Boolean value of True. Otherwise, it returns False.

>>> all(('1',1,True,''))

Output

False

7. sorted()

This function returns a sorted version of the tuple. The sorting is in ascending order, and it doesn’t modify the original tuple in Python.

>>> sorted(a)

Output

[1, 2, 3, 4, 5, 6]

8. tuple()


This function converts another construct into a Python tuple. Let’s look at some of those.

>>> list1=[1,2,3]
>>> tuple(list1)

Output

(1, 2, 3)
>>> string1="string"
>>> tuple(string1)

Output

(‘s’, ‘t’, ‘r’, ‘i’, ‘n’, ‘g’)

How well would it work with sets?

>>> set1={2,1,3}
>>> tuple(set1)

Output

(1, 2, 3)
>>> set1

Output

{1, 2, 3}

As we can see, when we declared a set as 2,1,3, it automatically reordered itself to 1,2,3. Furthermore, creating a Python tuple from it returned the new tuple in the new order, that is, ascending order.

Python Tuple Methods

A method is a sequence of instructions to perform on something. Unlike a function, it does modify the construct on which it is called. You call a method using the dot operator in python. Let’s learn about the two in-built methods of Python.

1. index()

This method takes one argument and returns the index of the first appearance of an item in a tuple. Let’s take a new tuple.

>>> a=(1,2,3,2,4,5,2)
>>> a.index(2)

Output

1

As you can see, we have 2s at indices 1, 3, and 6. But it returns only the first index.

2. count()

This method takes one argument and returns the number of times an item appears in the tuple.

>>> a.count(2)

Output

3

Python Tuple Operations

Now, we will look at the operations that we can perform on tuples in Python.

1. Membership

We can apply the ‘in’ and ‘not in’ operators on items. This tells us whether they belong to the tuple.

>>> 'a' in tuple("string")

Output

False
>>> 'x' not in tuple("string")

Output

True

2. Concatenation

Like we’ve previously discussed on several occasions, concatenation is the act of joining. We can join two tuples using the concatenation operator ‘+’.

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

Output

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

Other arithmetic operations do not apply on a tuple.

3. Logical

All the logical operators (like >,>=,..) can be applied on a tuple.

>>> (1,2,3)>(4,5,6)

Output

False
>>> (1,2)==('1','2')

Output

False

As is obvious, the ints 1 and aren’t equal to the strings ‘1’ and ‘2’. Likewise, it returns False.

4. Identity

Remember the ‘is’ and ‘is not’ operators we discussed about in our tutorial on Python Operators? Let’s try that on tuples.

>>> a=(1,2)
>>> (1,2) is a

Output

False

That did not make sense, did it? So what really happened? Well, in Python, two tuples or lists do not have the same identity. In other words, they are two different tuples or lists. As a result, it returns False.

Iterating on a Python Tuple

You can iterate on a Python tuple using a for loop like you would iterate on a list.

>>> for i in (1,3,2):
    print(i)

Output

1
3
2

Nested Tuples in Python

Finally, we will learn about nesting tuples. You may remember how we can nest lists. Due to the similarities of a tuple to a list, we do the same with tuples.

>>> a=((1,2,3),(4,(5,6)))

Suppose we want to access the item 6. For that, since we use indices, we write the following code.

>>> a[1][1][1]

Output

6

Python tuple may also contain other constructs, especially, lists. After all, it is a collection of items, and items can be anything.

>>> (1,2,[3,4])

Output

(1, 2, [3, 4])

This was all on Python Tuple Tutorial. Hope you like our explanation.

Python Interview Questions on Python Tuples

  1. What is tuples in Python?
  2. How do tuples work in Python?
  3. How do you initialize a tuple in Python?
  4. What is the difference between a Python Tuple and Python list?
  5. Why do we use tuples in Python?

Conclusion

Hence, today, we learned about creating tuples in Python. In that, we looked at tuple packing and unpacking, and how to create a tuple with just one item.

Then we talked about how to access, slice, delete, and reassign a tuple. After that, we looked at the inbuilt functions and methods that we can call on a tuple.

Lastly, we learned about the operations we can perform on a Python tuple, how to iterate on it, and nested tuples. Try them in the shell and leave your honest comments.

Did you like this article? If Yes, please give DataFlair 5 Stars on Google

follow dataflair on YouTube

12 Responses

  1. Sakshi raikwar says:

    very good and easy to understand

    • DataFlair Team says:

      Hello Sakshi,
      We are glad that you like our explanation on Python Tuples. We have 100+ Python Tutorials, with Python Interview Questions. Please refer them too and also share with your peer groups.
      Keep learning and keep exploring DataFlair

    • Vipin Kumar says:

      Very nice work done by you

  2. mohdmajid says:

    Sir or mam
    Thank you so much and it is really so easy to understand and I understood everything now.
    Thanks for helping and I hope you will keep doing it…..

    • DataFlair Team says:

      Thank for liking Python Tuple article. Will definitely keep posting more technologies and articles. Stay with DataFlair for more learning!!!

  3. Sandeep says:

    fentastic job!!! data-flair Team..
    your content is the best all over the internet for python

  4. Gollapalli Spandana says:

    fantastic articles.Really useful to build strong basics.Thank you so much!

    • DataFlair Team says:

      We are glad you liked our Python tutorials. You can also share our Python tutorial series with your friends on social media platforms.

  5. Hassaan Raheem says:

    converting string ,list in to tuple shows error in my python3 interpreter but in your site would show the outputs. which is right i am confused for guessing both options. plz reply my comment

    • DataFlair Team says:

      Hey Hassaan Raheem,

      The python 3 has a tuple function which converts an iterable into a tuple
      for example:
      tuple(“hello”) will print (‘h’, ‘e’, ‘l’, ‘l’, ‘o’)
      and tuple([1,2,3]) will result in (1, 2, 3)
      If you are getting anything else then show us your message so that we can look into it.

  6. Ali Fahmi says:

    This tutorial is very helpful and touches all parts of tuples.

Leave a Reply

Your email address will not be published. Required fields are marked *