A Handy Guide to Python Tuples

Python is a widely used, high-level, general-purpose programming language, particularly suited for developing GUI and web applications. It is also a very attractive choice for application development because it offers dynamic typing and binding options. In this article, we will be learning about an important data structure in Python programming: tuples.

The following topics will be discussed in this article:

  • What is Python?
  • Introduction to Python tuples 
  • How to create a Python tuple
  • How to access items from a tuple
  • Different tuple operations 
  • A selection of tuple methods
  • The differences between lists and tuples
  • Conclusion

What Is Python?

Python is a powerful, high-level, easy-to-learn programming language. Thanks to outstanding characteristics such as object-oriented, open-sourced, and having numerous IDE’s, it is one of the most in-demand programming languages in today’s IT industry. One of Python’s main advantages is that it provides excellent library support and has a large developer community. Python also provides easy integration with web services and GUI-based desktop applications.

python

Introduction to Python Tuples

A Python tuple is an immutable ordered sequence of items. In other words, existing objects in the sequence cannot be modified, and new elements cannot be added once the sequence is created. A tuple consists of several values separated by commas. Unlike a Python list, tuples are enclosed within parentheses “( )”. 

Python Training Course

Learn Data Operations in PythonExplore Course
Python Training Course

How to Create a Python Tuple

A Python tuple is created by using parentheses separated by commas. A tuple can hold multiple data types.

Syntax: tuple_name = (“element1”, “element2”, “element3”)

Example:

/create-tuple

Fig: Creating a Python Tuple

Nested Python Tuples

We can also nest a tuple or a list inside a Python tuple. The below-mentioned example illustrates this.

Example:

nested-tuple

Fig: Nested tuple

We can see the type of class being used by employing the type() method.

type-class

Fig: To know the type of class in a tuple

How to Access Items From a Tuple

We can access a tuple’s elements by referring to the index number. Remember that the index in a Python tuple starts from ‘0’.  To access elements in a tuple, we provide the index (as integer) inside the square brackets ( [ ] ), as shown below. 

access-item

Fig: Access item from a tuple

To access the elements from the end of the tuple, we use negative indexing. So, -1 means the last element, -2 the second last element, and so on.

For example: If we want to access the 4th element from the end of the tuple named ‘city’, we write city[-4].

 end-tuple

Fig: To access an element from the end of a tuple

We can also access the elements from a specific range.

Syntax: tuple_name[starting index : ending index]

access-elements

Fig: To access elements within a specific range in a tuple

Remember that the first item is position 0. 

Note: The search will start at index 1 (included) and end at index 4 (not included)

If we leave out the starting value, the range will begin from 0th index. Example:

zero-index

Fig: To access elements from 0th index

Nested tuples are accessed using nested indexing, as shown in the example below.

access-elements-nested

Fig: To access elements inside a nested tuple

Different Tuple Operations

Let’s take a look at a selection of tuple operations.

How to change and add elements to the tuple

We cannot add or change the item in a tuple once it is created. Any attempt to do so produces an error message. The following example illustrates the point.

error-message

Fig: Error message when attempting to change a tuple

Fig: Error message trying to add elements to a tuple

But there is a trick. You can convert a tuple into a list, add or modify the element, then change it back to a tuple, as the following example illustrates.

modify-elelment.

Fig: Modify an element in a tuple

In the example above, we first converted the tuple ‘city’ into a list with the name ‘newcity’. Now we can change the element value by specifying the index number and replacing it with a new element. Then we converted the list ‘newcity’ back to tuple ‘city’.  

Similarly, we can add the element in a tuple. For this, we use the append () method.

add-element

Fig: To add an element in a tuple

We can also change the element of a list inside a tuple.

Syntax: tuple_name [index of list in the tuple] [index of element inside a list]

Example:

modifylist

Fig: To modify a list inside a tuple

Now that we know how to create and access items from tuples, let’s move on and see how to add and delete elements from tuples.

How to Delete Elements From a Tuple

There are limitations when it comes to deleting in Python tuples. We cannot delete items directly from a tuple; this results in an error message. This happens because the remove() method is not a tuple attribute.

error-message-2

Fig: Error message when trying to delete an element from a tuple

How to Check for an Item Existing in Tuple

We can check to see if a particular item exists in a tuple. The example below shows how it can be done.

Syntax: if “element_name “ in  list_name :

Fig: To check if item exists in the tuple

How to Check the Length of a Tuple

You check the length of the tuple by using the len() method.

Syntax: print(len(tuple_name))

Example:

check-length

Fig: To check the length of a tuple

How to Join Two Tuples

You can join two tuples by using the ‘+’ operator.

Syntax: tuple_1 + tuple_2

Example:

join-two

Fig: To join two tuples

A Selection of Tuple Methods

Python supports a range of useful in-built methods that can be used inside a tuple.

Here are some examples of these functions:

  • count()

The count() method returns the number of times a specified value has occurred in a tuple.

Syntax: print(tuple_name.count(“element”))

Example:

count

Fig: count() method in a tuple

  • index()

The index() method returns the position of the specified element.

Syntax: print(tuple_name.index(“element”))

Example:

index

Fig: index() method in a tuple

  • min()

The min() method returns the minimum value in a numerical tuple.

min

Fig: min() method in a tuple

  • max()

The max() method returns the maximum value in a numerical tuple.

max 

Fig: max() method in a tuple

  • sum()

The sum() method adds all the values in a numerical tuple.

sum

Fig: sum () method in a tuple

The Differences Between Lists and Tuples

List

Tuple

It’s mutable

It’s immutable

Lists come in variable lengths

Tuples are fixed length

Lists consume more memory

Tuples consume less memory

List operations are more error-prone

Tuple operations are safe

Learn data operations in Python, strings, conditional statements, error handling, and the commonly used Python web framework Django with the Python Training course.

Conclusion

Python tuples are very convenient for constructing and accessing individual elements in programming. To learn more about Python tuples, visit the link:  https://www.youtube.com/watch?v=wRC4H-k57eg.

If you have any questions or comments, please share them in the comment section of the article, and we’ll have our experts get back to you.

Want to Kickstart Your Career in Data Science?

Python is an indispensable skill for any data scientist—and data scientists are in super high demand. If you’re interested in joining this exciting field, consider enrolling in our Data Science with Python Course, which is co-developed with IBM.

About the Author

SimplilearnSimplilearn

Simplilearn is one of the world’s leading providers of online training for Digital Marketing, Cloud Computing, Project Management, Data Science, IT, Software Development, and many other emerging technologies.

View More
  • Disclaimer
  • PMP, PMI, PMBOK, CAPM, PgMP, PfMP, ACP, PBA, RMP, SP, and OPM3 are registered marks of the Project Management Institute, Inc.