Python Tuples Tutorial

Python Tuples Tutorial

Last updated on 26th Sep 2020, Blog, Tutorials

About author

Ammer (Sr Technical Project Manager )

High level Domain Expert in TOP MNCs with 8+ Years of Experience. Also, Handled Around 16+ Projects and Shared his Knowledge by Writing these Blogs for us.

(5.0) | 16552 Ratings 905

Python tuples: Introduction

Just like Python list, tuples are also the sequence of comma-separated values enclosed in parentheses instead of square brackets. The parentheses are optional though.

Here is an example of a tuple in Python.

  • py_tuple = (1,2,’a’,’b’,’Hello’)

Python tuples contain ordered sequence of items that can be of different data types.

Tuples are immutable, which means a tuple cannot be modified once it is created

Python Tuples Tutorial

Learn about Python tuples: what they are, how to create them, when to use them, what operations you perform on them and various functions you should know.

Similar to Python lists, tuples are another standard data type that allows you to store values in a sequence. They might be useful in situations where you might want to share the data with someone but not allow them to manipulate the data. They can however use the data values, but no change is reflected in the original data shared.

In this tutorial, you will see Python tuples in detail:

  • You will learn how you can initialize tuples. You will also see the immutable nature of tuples through examples;
  • You’ll also discover how a tuple differs from a Python list;
  • Then, you will see the various tuple operations, such as slicing, multiplying, concatenating, etc.;
  • It is helpful to know some built-in functions with tuples and you will see some important ones in this section.
  • Finally, you’ll see that it is also possible to assign multiple values at once to tuples.

What are Tuples in Python?

Tuples are collections of Python objects. They are similar to lists but the difference between them is that tuples are immutable while lists are mutable.

Learn to store multiple values in Python using TechVidvan’s Python Lists article.

How to Create Tuples in Python?

Tuples are created by typing a sequence of items, separated by commas. Optionally, you can put the comma-separated values in parenthesis.

Python Tuple with example

In Python, a tuple is similar to List except that the objects in tuple are immutable which means we cannot change the elements of a tuple once assigned. On the other hand, we can change the elements of a list.

Tuple vs List

    1. 1. The elements of a list are mutable whereas the elements of a tuple are immutable.
    2. 2. When we do not want to change the data over time, the tuple is a preferred data type whereas when we need to change the data in future, list would be a wise option.
    3. 3. Iterating over the elements of a tuple is faster compared to iterating over a list.
    4. 4. Elements of a tuple are enclosed in parenthesis whereas the elements of list are enclosed in square bracket.

How to create a tuple in Python

To create a tuple in Python, place all the elements in a () parenthesis, separated by commas. A tuple can have heterogeneous data items, a tuple can have string and list as data items as well.

Example – Creating tuple

In this example, we are creating few tuples. We can have tuple of same type of data items as well as mixed type of data items. This example also shows nested tuple (tuples as data items in another tuple).

  • # tuple of strings
  • my_data = (“hi”, “hello”, “bye”)
  • print(my_data)
  • # tuple of int, float, string
  • my_data2 = (1, 2.8, “Hello World”)
  • print(my_data2)
  • # tuple of string and list
  • my_data3 = (“Book”, [1, 2, 3])
  • print(my_data3)
  • # tuples inside another tuple
  • # nested tuple
  • my_data4 = ((2, 3, 4), (1, 2, “hi”))
  • print(my_data4)

Output:

  • (‘hi’, ‘hello’, ‘bye’)
  • (1, 2.8, ‘Hello World’)
  • (‘Book’, [1, 2, 3])
  • ((2, 3, 4), (1, 2, ‘hi’))

Empty tuple

  • # empty tuple
  • my_data = ()

Tuple with only single element

Note: When a tuple has only one element, we must put a comma after the  element, otherwise Python will not treat it as a tuple.

Subscribe For Free Demo

Error: Contact form not found.

  • # a tuple with single data item
  • my_data = (99,)

If we do not put comma after 99 in the above example then python will treat my_data as an int variable rather than a tuple.

How to access tuple elements

We use indexes to access the elements of a tuple. Lets take few example to understand the working.

Accessing members of Python tuples.Here are the most common ways to access members in Python tuples.

Indexing

Likewise in Python list, in Python tuples as well, indexing operator [ ] is used for accessing the members.Once created we cannot modify the tuple since they are immutable, but we can use the members for the further operations. For this, Python has indexing operator ‘[ ]’. Index starts from 0.

For example, if we have a tuple named py_tuple, we can access its 6th element by using py_tuple[5] as the indexing starts from 0.

Note: Only integers can be used to index, floating point numbers are not allowed.

There are two ways we can index tuples in Python:

index with positive integers: Index from left starting with 0 and 0 indexing first item in the tuple index with negative integer: Index  from the right starting with -1 and -1 indexing the last item in the tuple

Accessing tuple elements using positive indexes

We can also have negative indexes in tuple, we have discussed that in the next section. Indexes starts with 0 that is why we use 0 to access the first element of tuple, 1 to access second element and so on.

  • # tuple of strings
  • my_data = (“hi”, “hello”, “bye”)
  • # displaying all elements
  • print(my_data)
  • # accessing first element
  • # prints “hi”
  • print(my_data[0])
  • # accessing third element
  • # prints “bye”
  • print(my_data[2])

Output

  • (‘hi’, ‘hello’, ‘bye’)
  • hi
  • bye

TypeError:

If you do not use integer indexes in the tuple. For example my_data[2.0] will raise this error. The index must always be an integer.

IndexError:

Index out of range. This error occurs when we mention the index which is not in the range. For example, if a tuple has 5 elements and we try to access the 7th element then this error would occurr.

Negative indexes in tuples

Similar to list and strings we can use negative indexes to access the tuple elements from the end.

-1 to access last element, -2 to access second last and so on.

  • my_data = (1, 2, “Kevin”, 8.9)
  • # accessing last element
  • # prints 8.9
  • print(my_data[-1])
  • # prints 2
  • print(my_data[-3])

Output

  • 8.9
  • 2

Accessing elements from nested tuples

Lets understand how the double indexes are used to access the elements of nested tuple. The first index represents the element of main tuple and the second index represent the element of the nested tuple.

In the following example, when I used my_data[2][1], it accessed the second element of the nested tuple. Because 2 represented the third element of main tuple which is a tuple and the 1 represented the second element of that tuple.

  • my_data = (1, “Steve”, (11, 22, 33))
  • # prints ‘v’
  • print(my_data[1][3])
  • # prints 22
  • print(my_data[2][1])

Output

  • v
  • 22

Operations that can be performed on tuple in Python

Lets see the operations that can be performed on the tuples in Python. 

Changing the elements of a tuple

We cannot change the elements of a tuple because elements of tuple are immutable. 

However we can change the elements of nested items that are mutable. For example, in the following code, we are changing the element of the list which is present inside the tuple. List items are mutable that’s why it is allowed.

Accessing Tuple

The values of tuples are stored at different index positions starting from zero. 

We can access the values by using their index positions inside square brackets.

Changing Tuple Values

As we said earlier that tuples are immutable which means that once a tuple is created we cannot change its value.

Tuple-In-Python

1. len()

The len() function returns us the length of a sequence or a container. It is applicable on tuples also.

2. max()

The max() function returns us the maximum element from a sequence or container. The elements must contain all numbers or all characters.

3. min()

The min() function returns the minimum value from group of elements.

4. sum()

The sum() function calculates the total sum of all elements and returns it. It can only be used on numeric values.

5. tuple()

The tuple() function converts an iterable like a list, set, string into an immutable tuple.

6. sorted()

The sorted() function sorts the elements in ascending order. It takes an iterable like a tuple and returns a list of sorted elements.

python Sample Resumes! Download & Edit, Get Noticed by Top Employers! Download

Find the index of particular item in the tuple

We can find the index of a particular item in the Python tuples by using the following function.

  • tuple_name.index(item_name)

Where item_name is the name of the item whose index is to be found.

This function will return the index of the first appearance of that particular item in the tuple.

  • >>> py_tuple = (‘a’,’b’,’c’,’d’)
  • >>> #to find the index of b
  • >>> py_tuple.index(‘b’) #this will return 1 as 1 is the index of b’s first appearance

Deleting a Python tuple

Since Python tuples are immutable, we cannot deleting particular items. However we can delete entire tuple using function del.

  • >>> py_tuple = (1,2,3,4,5)
  • >>> #to delete the tuple
  • >>> del py_tupl

Reverse the order of items in the Python tuple

To reverse the order of elements in the tuple, Python has an inbuilt function tuple_name.reverse( ), which reverses the order of appearance of elements in the tuple.

  • >>> py_tuple = (2,4,6,8)
  • >>> #to reverse the order of appearance of elements
  • >>> py_tuple.reverse() #this will make the tuple as (8,6,4,2)

Count the appearance of an item in the Python tuple

To count the appearance of an item in the tuple , Python has an inbuilt function tuple_name.count(item_name), which returns the number of times the item appears in the tuple.

  • >>> py_tuple = (1,2,3,3,3,4)
  • >>> #to count the appearance of 3
  • >>> py_tuple.count(3) #this will return 3
  • 3

Finding largest and smallest items in a Python tuple

Python has built in function max( ) and min( ) to find the maximun and minimum item from any sequence.

  • >>> py_tuple = (1,2,3,4)
  • >>> #to find the maximum and the minimum item from the tuple
  • >>> max(py_tuple) #this will return 4
  • 4
  • >>> min(py_tuple) #this will return 1
  • 1

So, this all about Python tuples and different functional operations related to tuples.

BEGINNERSBOOK.CO

Are you looking training with Right Jobs?

Contact Us

Popular Courses