Home » Python Tuples: A Complete Guide
Coding Technology

Python Tuples: A Complete Guide

Python Tuples
Python Tuples

Python Tuples: When working with data collection we occasionally encounter situations where we want to ensure it’s impossible to change the sequence of objects after creation.

For instance, when reading data from a database in Python, we can represent each table record as an ordered and unchangeable sequence of objects since we don’t need to alter the sequence later. Python has a built-in sequence data type to store data in an unchangeable object, called a tuple.

  • After you finish this Python tutorial, you’ll know the following:
  • How to work with tuples in Python
  • The difference between tuples and lists in Python

Table of Content

Python Tuples Basics

In this tutorial, we assume you know the fundamentals of Python, including variables, data types, and basic structures. If you’re not familiar with these or would like to review them, you might like to try our Python Basics for Data Analysis – Dataquest. Let’s Drive-in into the topic in detail.

Understanding Python Tuples

Tuples are used to store multiple items in a single variable. A tuple is one of 4 built-in data types in Python used to store collections of data, the other 3 are List, Set, and Dictionary, all with different qualities and usage. A tuple is a collection that is ordered and unchangeable.

When thinking about Python tuples and other data structures that are types of collections, it is useful to consider all the different collections you have on your computer: your assortment of files, your song playlists, your browser bookmarks, your emails, the collection of videos you can access on a streaming service, and more.

Tuples are similar to lists, but their values can’t be modified. Because of this, when you use tuples in your code, you are conveying to others that you don’t intend for there to be changed to that sequence of values. Additionally, because the values do not change, your code can be optimized through the use of tuples in Python as the code will be slightly faster for tuples than for lists.

How to Access Tuple Items

A Python Tuple is an ordered collection of items and also an iterable. Therefore, we can read the values of items using the index, or iterate over items using for loop or while loop.

In this tutorial, we will learn how to read items of a tuple using an index or iterate over the items using a looping technique.

Tuple Slicing

We can use slicing in tuples I’m the same way we use in strings and lists. Tuple slicing is basically used to obtain a range of items. Furthermore, we perform tuple slicing using the slicing operator. We can represent the slicing operator in the syntax [start:stop:step]. Moreover, it is not necessary to mention the ‘step’ part. The compiler considers it 1 by default if we do not mention the step part. Let us look at the examples to understand tuple slicing in detail

Code

>>> tup = (22, 3, 45, 4, 2.4, 2, 56, 890, 1)

>>> print(tup[1:4])

# prints 2nd to 4th element

Output: (3, 45, 4)

Slicing with a negative index

There is also a feature of tuple slicing called stride. This feature allows us to skip over items after the first item is retrieved from a tuple. If we want to use stride, we can add value to the end of our slicing function. This states how many items the list should skip over between increments. So if we wanted to get every second number in our tuple, we could use the following code:

Code

# Creating a List

List = ['T', 'O',' P', 'P', 'R', 'F',

'O',' R', 'T', 'O',' P', 'P', 'R']

print("Initial List: ")

print(List)

# Print elements from the beginning

# to a pre-defined point using Slice

Sliced_List = List[:-6]

print("\nElements sliced till 6th element from last: ")

print(Sliced_List)

# Print elements of a range

# using negative index List slicing

Sliced_List = List[-6:-1]

print("\nElements sliced from index -6 to -1")

print(Sliced_List)

# Printing elements in reverse

# using Slice operation

Sliced_List = List[::-1]

print("\nPrinting List in reverse: ")

print(Sliced_List)

Python Tuple operators

There are three standard sequence operations (+, *, []) that can be performed with tuples as well as lists and strings. The + operator creates a new tuple as the concatenation of the arguments. Here’s an example.

>>>

(“chapter”,8) + (“strings”, “tuples”, “lists”)

(‘chapter’, 8, ‘strings’, ‘tuples’, ‘lists’)

The * operator between tuples and numbers (number * tuple or tuple * number) creates a new tuple that is a number of repetitions of the input tuple.

>>>

2*(3,”blind”,”mice”)

(3, ‘blind’, ‘mice’, 3, ‘blind’, ‘mice’)

The [] operator selects an item or a slice from the tuple. There are two forms. The first format is tuple [ index ]. Items are numbered from 0 at the beginning through the length. They are also numbers from -1 at the end backward to -len( tuple ). The sliced format is tuple [ start: end ]. Elements from start to end -1 are chosen; there will be end-start elements in the resulting tuple. If the start is omitted, it is the beginning of the tuple (position 0), if the end is omitted, it is the end of the tuple (position -1).

>>>

t=( (2,3), (2, “hi”), (3, “mom”), 2+3j, 6.02E23 )

>>>

t[2]

(3, ‘mom’)

>>>

print t[:3], ‘and’, t[3:]

((2, 3), (2, ‘hi’), (3, ‘mom’)) and ((2+3j), 6.02e+23)

>>>

print t[-1], ‘then’, t[-3:]

6.02e+23 then ((3, ‘mom’), (2+3j), 6.02e+23)

Iterating Through a Tuple

There are different ways to iterate through a tuple object. The statement in Python has a variant that traverses a tuple till it is exhausted. It is equivalent to each statement in Java. Its syntax is −

for var in a tuple

stmt1

stmt2

Example

The following script will print all items in the list…

T = (10,20,30,40,50)

for var in T:

print (T.index(var),var)

Output

The output generated is −

0 10

1 20

2 30

3 40

4 50

Another approach is to iterate over the range up to the length of the tuple and use it as an index of items in the tuple.

Example

for var in range(len(T)):

  print (var,T[var])

You can also obtain enumerate object from the tuple and iterate through it.

Output

The following code gives the same output.

for var in enumerate(T):

  print (var)

Lists vs Python Tuples

#1 Tuples and lists are both used to store the collection of data

#2 Tuples and lists are both heterogeneous data types means that you can store any kind of data type

#3 A Tuples and lists are both ordered means the order in which you put the items is kept

#4 Tuples and lists are both sequential data types so you can iterate over the items contained

#5 Items of both tuples and lists can be accessed by an integer index operator, provided in square brackets, [index].

Let’s check this in the code block below

import sys

a_list = list()

a_tuple = tuple()

a_list = [1,2,3,4,5]

a_tuple = (1,2,3,4,5)

print(sys.getsizeof(a_list))

print(sys.getsizeof(a_tuple))

Output

104 (bytes for the list object

88 (bytes for the tuple object)

As you can see from the output of the above code snippet, the memory required for the identical list and tuple objects is different. When it comes to time efficiency, again tuples have a slight advantage over the lists especially when we consider lookup value.

import sys, platform

import time

print(platform.python_version())

start_time = time.time()

b_list = list(range(10000000))

end_time = time.time()

print("Instantiation time for LIST:", end_time - start_time)

start_time = time.time()

b_tuple = tuple(range(10000000))

end_time = time.time()

print("Instantiation time for TUPLE:", end_time - start_time)

start_time = time.time()

for item in b_list:

  aa = b_list[20000]

end_time = time.time()

print("Lookup time for LIST: ", end_time - start_time)

start_time = time.time()

for item in b_tuple:

  aa = b_tuple[20000]

end_time = time.time()

print("Lookup time for TUPLE: ", end_time - start_time)

Output

3.6.9

Instantiation time for LIST: 0.4149961471557617

Instantiation time for TUPLE: 0.4139530658721924

Lookup time for LIST:  0.8162095546722412

Lookup time for TUPLE:  0.7768714427947998

Conclusion

This tutorial covered how to create tuple objects as well as many aspects of Python tuples such as Tuple slicing, slicing with negative index numbers, Tuple operators, etc. We also discussed the difference between tuples and lists. Using Python tuples properly will definitely make our code more efficient and robust. Hope you found this blog helpful and if it is so share your thought in the comment section. Follow Publish Square for more blogs like this.

About the author

Ashwini

A Content Writer at PublishSquare who is passionate about Seo, Creative Writing, Digital Marketing with 2+ years of experience in Content Creation for blogs and social media.