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

1. Python Tuple Tutorial

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

2. 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.

3. 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.

a. Python Tuples Packing

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

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

b. 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

90

You can do the same to a list.

c. 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)

<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)

<class ‘tuple’>

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

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

<class ‘tuple’>

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

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

4. How to Access Python Tuple?

a. Accessing the entire tuple

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

>>> percentages

(90, 95, 89)

Or, pass it to the print statement.

>>> print(percentages)

(90, 95, 89)

b. 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]

95

5. 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)

a. Positive Indices

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

>>> percentages[2:4]

(90, 89)

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

>>> percentages[:4]

(99, 95, 90, 89)

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

>>> percentages[4:]

(93, 96)

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

>>> percentages[2:2]

()

However, this returns an empty Python tuple.

b. Negative indexing

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

>>> percentages[:-2]

(99, 95, 90, 89)

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

>>> percentages[-2:]

(93, 96)

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

>>> percentages[2:-2]

(90, 89)

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

>>> percentages[-2:2]

()

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[:]

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

6. 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]

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]

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

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.

7. 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

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

(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.

8. 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

a. len()

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

>>> my_tuple

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

>>> len(my_tuple)

4

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

b. 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)

6

Let’s try that on strings.

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

‘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))

Traceback (most recent call last):

File “<pyshell#59>”, line 1, in <module>

max((‘Hi’,9))

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

c. min()

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

>>> min(a)

1

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

d. sum()

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

>>> sum(a)

21

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

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

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’

e. 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',''))

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,''))

False

f. all()

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

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

False

g. 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)
[1, 2, 3, 4, 5, 6]

h. tuple()

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

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

(1, 2, 3)

>>> string1="string"
>>> tuple(string1)

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

How well would it work with sets?

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

(1, 2, 3)

>>> set1

{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.

9. 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.

a. 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)

1

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

b. count()

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

>>> a.count(2)

3

10. Python Tuple Operations

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

a. 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")

False

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

True

b. 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)

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

Other arithmetic operations do not apply on a tuple.

c. Logical

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

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

False

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

False

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

d. 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

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.

11. 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)

1
3
2

Python Interview Questions

12. 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]

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])

(1, 2, [3, 4])

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

13. 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.

Reference

2 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

Leave a Reply

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

This site is protected by reCAPTCHA and the Google Privacy Policy and Terms of Service apply.