Home Python Tuples in Python

Tuples in Python

In this article, you will learn about Python tuples, including what they are, how to create them, when to use them, the operations you can perform on them, and the various functions you should be familiar with.

Tuples, like Python lists, are a standard data type that allows you to store values in a sequence. They could be helpful when you want to share data with someone but not allow them to manipulate it.

Tuples are a type of variable that allows you to store several elements in a single variable.

The tuple is one of Python’s four built-in data types for storing data collections; the other three are List, Set, and Dictionary, all of which have different properties and applications. In addition, a tuple is a collection of items that is both ordered and immutable. Further, round brackets are used to write tuples.

They can use the data values, but no change is reflected in the original shared data.

Data structures are essential components of any programming language. Therefore, to build robust and high-performing products, one must be well-versed in data structures.

This post will look at a crucial data structure in the Python programming language: the tuple. A tuple is a group of values separated by commas and enclosed in parenthesis. Tuples, unlike lists, are immutable.

The immutability of tuples can be regarded as a distinguishing feature.

In this tutorial, you will learn about Python tuples in-depth:

You will discover how to initialize tuples. You will also see how immutable tuples are and how a tuple differs from a Python list. Then you’ll see tuple operations like slicing, multiplying, concatenating, and so on;

Some built-in tuple functions are helpful, and you’ll examine some of the most significant ones in this section.

Finally, you’ll see that tuples can have several values assigned to them at the same time. In addition, we’ll use examples to explain the characteristics of tuples and operations on them.

Tuples in Python

As previously stated, you may use this Python data structure to store an immutable (or unchangeable) and ordered series of things.

Tuples are started with () brackets instead of [] brackets like lists. That implies all you have to do to make one is perform the following:

define_tuple = ('n','e','w','t','u','p','l','e')
print(type(define_tuple))
checking type of tuple

Keep in mind that type() is a built-in function that can determine the data type.

Both homogeneous and heterogeneous values can be stored in a tuple. However, keep in mind that once you’ve defined your values, you won’t be able to edit them:

define_mixed_type = ('t',9,2,'u','P','l','e',8,3,'f')


for i in define_mixed_type:
  print(i,":",type(define_mixed_type))
  
  
define_mixed_type[1] = 'P'
homogeneous and heterogeneous values in a tuple

Because you can’t alter the values within a tuple, you receive this last error notice.

Another technique to make a tuple is as follows:

define_numbers_tuple = 4,5,6,7,8
print(type(define_numbers_tuple ))
Creating a tuple
Creating a tuple

Tuple Operations Commonly in Python

You can modify tuples in Python in a variety of ways. Let’s take a look at a few of the essential ones, along with some examples.

Making tuples

Tuples are made up of values enclosed in parenthesis and separated by a comma.

define_tuple= (9, 8)
print(type(define_tuple))
Making tuples
Making tuples

Tuples can store values of various data types as well as duplicate values.

define_tuple = (9, 9, 'x', [7,8])
print(define_tuple)

print(type(define_tuple))
store duplicate values in a tuple
store duplicate values in a tuple

We can also make tuples without the use of parenthesis. A tuple is formed by a series of values separated by commas.

define_tuple = 6, 7, 8, 9
print(type(define_tuple))
tuple is formed by a series of values separated by commas
the tuple is created by a series of values separated by commas

Making a tuple with either 0 or 1 element

A tuple with zero elements is simply an empty one, and it is formed as follows:

define_tuple = ()
print(type(define_tuple))
A tuple with zero elements
A tuple with zero elements

There is, however, a simple trick for creating a tuple with only one element. After the element, a comma is required. Otherwise, you will create a variable of the value’s type.

define_tuple = (6)
print(type(define_tuple))

define_tuple_two = ([4,5])
print(type(define_tuple_two))
creating a tuple with only one element without a comma
creating a tuple with only one element without a comma

Let’s try it again, but this time with a comma after the values:

define_tuple = (6,)
print(type(define_tuple))

define_tuple_two = ([4,5],)
print(type(define_tuple_two))
creating a tuple with only one element with a comma
creating a tuple with only one element with a comma

Tuples can be iterated

You can iterate over a tuple in the same way that you can iterate over a list.

define_tuple = (1, 2, 3)
for tup in define_tuple:
  print(tup**2)
iteration in tuples
iteration in tuples

Slicing and indexing

Tuples are indexed and sliced in the same way as lists are.

define_tuple = (6, 8, 'x', 8)

print(f'The first element of tuple define_tuple is {define_tuple[0]}')
print(f'The last element of tuple define_tuple is {define_tuple[-1]}')
indexing in tuples
indexing in tuples

Slicing examples

define_tuple = (4, 5, 8, 9, 10)
print(define_tuple [-2:])

print(define_tuple [:3])
Slicing examples
Slicing examples

Tuples are immutable, although their elements can be changed

Tuples’ immutability may be their most distinguishing trait. A tuple’s items cannot be assigned.

define_tuple = (6, 8, 'x', 8)
define_tuple[0] = 7 #error
Tuples immutability
Tuples immutability

Tuples, on the other hand, can contain mutable items like lists.

define_tuple = ([4,5], ['x', 'y'])
define_tuple[0][0] = 68
define_tuple[1][0] = 't'
print(define_tuple)
tuples can contain mutable items like lists
tuples can have mutable items like lists

Sort vs. sorted

We can’t order tuples using sort because they’re immutable:

define_tuple = (6, 0, 5)
define_tuple.sort() #error
cannot order tuples using sort
cannot order tuples using sort

On the other hand, the sorted function can accept a tuple as an input and return a sorted list of the tuple’s values. It is essential to notice that this method does not produce a sorted tuple. The return variable’s type is the list.

define_tuple_one = (3, 5, 8, 2)
define_tuple_two = sorted(define_tuple_one)
print(define_tuple_two)

print(type(define_tuple_two))
using sorted to order  tuples
using sorted to order tuples

A tuple’s length

To find the length of a tuple, use the len function.

define_tuple = (3, 0, 2)
len(define_tuple)
A tuples length
A tuples length

Counting and indexing techniques

Tuples have techniques for counting and indexing. The count method returns the number of times a value appears in a tuple.

define_tuple = (4, 'x', 4, 4, 'x')
print(define_tuple.count('x'))

print(define_tuple.count(4))
Count() function in tuples
Count() function in tuples

The index method returns the tuple’s value’s index.

define_tuple = (4, 'x', 6, 8, 'x')
print(define_tuple.index('x'))

print(define_tuple.index(4))
index function in tuples
index function in tuples

If a value appears in a tuple numerous times, the index method returns the index of the first occurrence.

Concatenating tuples

To add tuples together, use the ‘+’ operator.

define_tuple_one = (1, 2)
define_tuple_two = ('x', 'y')
define_tuple_three = define_tuple_one + define_tuple_two
print(define_tuple_three )
Concatenating tuples
Concatenating tuples

Functions that return multiple values

Functions that return several values are one of the most popular uses of tuples. The total and count of items in an array are returned using the following procedure.

def count_sum(arr):
  count_val = len(arr)
  sum_val = arr.sum()
  return count_val, sum_val

This function returns a tuple with two elements:

import numpy as np
ran_array = np.random.randint(6, size=9)
define_tuple = count_sum(ran_array)
print(define_tuple)


print(type(define_tuple))
Functions that return multiple values
Functions that return multiple values

Other Tuple Operations

Multiplication of multiples

The tuple is repeated after the multiplication operation.

define_tuple = (4,5,6,7)
z = define_tuple*2
print(z)
Multiplication of multiples
Multiplication of multiples

Functions in Tuples

Tuples, unlike Python lists, lack methods like append(), remove(), extend(), insert(), and pop() due to their immutability. There are, however, a slew of other built-in tuple methods:

Index()

tuple.index(el)

The index method returns the index of the element’s first occurrence in a tuple.

define_tuple = (1, 44, 65, 74, 8, 54, 44)
print(define_tuple.index(1))

This method can also be used to return the index of the element’s last occurrence.

define_tuple = (1, 44, 65, 74, 8, 54, 44)
print(define_tuple.index(24, -1))

It’s also possible to search inside a specific range, as shown below.

define_tuple = (1, 44, 65, 74, 8, 54, 44)
print(define_tuple.index(44, 4, 7))

count() and len()

count() returns the number of times a given item appears in a tuple.

define_tuple = [4,5,6,7,8,8]
define_tuple.count(8)

You can get the length of a tuple using the len() function:

define_tuple = (4,5,6,7,8)
print(len(define_tuple))

Any()

It can be used to determine whether or not any element of a tuple is iterable. If this is the case, you’ll get true; otherwise, you’ll get False.

define_tuple = (1,)
print(any(define_tuple))

Take note of the comma in the tuple declaration above. When you don’t include a comma when initializing a single item in a tuple, Python guesses you added an extra pair of brackets by accident (which is fine), but the data type is no longer a tuple. So when declaring a single item in a tuple, remember to include a comma.

Returning to the any() method now: The value of an item is unimportant in a boolean context. Therefore, any tuple with at least one item is valid, while an empty tuple is false.

define_empty_tuple = ()
print(any(define_empty_tuple))

If you’re calling a tuple anywhere in your application and want to make sure it’s populated, this function can come in handy.

tuple()

To convert a data type to a tuple, use tuple(). For instance, you are converting a given list into a tuple. You can see an example of this in the code section below.

define_a_list = [3,5,6,7,8]
define_tuple = tuple(define_a_list)
print(type(define_tuple))
tuple()
tuple()

min() and max()

While max() delivers the tuple’s most significant element, you can use min() to get the tuple’s smallest element. Consider the following illustration:

print(max(a))
print(min(a))

It also works with tuples that include the string data type.

The string ‘Apple’ is automatically converted into a sequence of characters.

a = ('Apple')
print(max(a))

sum()

This function returns the total sum of the components in a tuple. It is only applicable to numerical numbers.

sum(a)

sorted()

Use sorted() to return a tuple with elements in sorted order, as shown in the following example:

define_tuple = (6,7,4,2,1,5,3)
sorted(define_tuple)

It’s important to note that the return type is a list rather than a tuple. The data type of ‘a’ remains a tuple, and the sequence in the original tuple ‘a’ is not modified.

cmp()

The cmp() tuple method in Python compares the elements of two tuples.

Syntax
The syntax for the cmp() method is as follows:

cmp (define_tuple1, define_tuple2)

Parameters

define_tuple1- This is the first tuple to be compared.

define_tuple2- This is the second tuple to be compared.

Return value

Perform the comparison and return the result if the items are of the same type. Check to see if the elements are numbers if they are of different types.

If there are numbers, use numeric coercion if necessary before comparing.

If one of the elements is a number, the other is “bigger” (numbers are “smallest”).

Types are arranged alphabetically by name otherwise.

If we get to the end of one of the tuples, the longer one is “larger.” If both tuples are exhausted and contain the same data, the result is a tie and 0 returns.

Example
The cmp() method is demonstrated in the following example.

define_tuple1, define_tuple2 = (312, 'xyz'), (645, 'abc')
print(cmp(define_tuple1, define_tuple2))
print(cmp(define_tuple2, define_tuple1))
define_tuple3 = define_tuple2 + (678,);
print (cmp(define_tuple2, define_tuple3))

Assigning Multiple Values

Tuples may be used to assign several values at the same time, which is an excellent feature. Take a look at this:

define_tuple = (1,2,3)
(first,second,third) = define_tuple
print(second)

The (first, second, third) is a tuple of three variables and a tuple having three elements. When you assign (first, second, third) to a tuple, it gives the values to variables one, two, and three in that sequence. It is useful when you need to assign a range of values to a series in a tuple.

Example:

def cmp(tuple_one, tuple_two):
    return bool( tuple_one > tuple_two) - bool( tuple_one < tuple_two)

tuple_one = (100, 200)
tuple_two = (300, 400)

print(cmp(tuple_one, tuple_two))

print(cmp(tuple_two, tuple_one))

tuple_one = (100, 200)
tuple_two = (100, 200)

print(cmp(tuple_two, tuple_one))


tuple_one = (100, 300)
tuple_two = (200, 100)

print(cmp(tuple_two, tuple_one))
cmp
cmp

Additional Information

Lists and tuples are both collections of values. Immutability is the most fundamental distinction.

Copying tuples and lists differ due to their immutability. Because lists are mutable, we must be more cautious while duplicating them. In addition, we can replicate a list and assign it to a new variable in one of three ways:

define_list = [4, 5, 6]
y = define_list
z = define_list[:]
t = define_list.copy()

The values in the lists y, z, and t are the same as define_list. On the other hand, Y points to the values of define_list, whereas z and t are entirely different lists.

As a result, any change in define_list will result in a change in y.

define_list.append(4)
print(y)
print(t)
replicate a list and assign it to a new variable
replicate a list and assign it to a new variable

When copying lists, we must exercise extreme caution. Tuples, on the other hand, should not raise the same concerns because they are immutable.
When you copy a tuple and assign it to a new variable, the values in memory are all the same.

define_tuple = (1, 2, 3)
b = define_tuple
c = a[:]

Test for Multiple Membership

Using the keyword in, we can determine whether or not an item exists in a tuple.

#testing for Membership in a tuple

define_tuple = ('a', 'p', 'p', 'l', 'e',)

# using 'In' operation

print('l' in define_tuple)
print('b' in define_tuple)


# using 'not in' operation
print('g' not in define_tuple)
print('e' not in define_tuple)
Test for Multiple Membership

Lists versus Tuples

Tuples are similar to lists, as you may have noticed. They are immutable lists, which implies that once a tuple is generated, the values of the elements stored in it cannot be deleted or changed. You can’t change any of the values.

define_tuple = (1,2,3,4,5)
define_list = [1,2,3,4,5]

# Append a number to the tuple
define_tuple.append(6)
tuples are immutable

Because you can’t remove or append to a tuple, but you can with a list, this results in an error.

# Append numbers to the list

define_list.append(9)
define_list.append(10)
define_list.append(11)

# Remove a number from the list

define_list.remove(9 )
print(define_list)
Append numbers to the list

But, if tuples are immutable, why would you utilize them?

They are not only faster than lists, but they also provide “read-only” access to the data values. Take a look at the following lines of code:

import timeit

timeit.timeit('x=(1,2,3,4,5,6,7,8,9)', number=100000)

timeit.timeit('x=[1,2,3,4,5,6,7,8,9]', number=100000)
read-only access in tuples
read-only access in tuples

What does immutable mean in the context of tuples?

Immutable is defined as “an object having a fixed value” in the official Python manual, although “value” is a somewhat ambiguous term; the correct time for tuples is “id.” The identity of the position of an object in memory is referred to as ‘id.’

Let’s take a closer look at this:

# Tuple 'define_a_tuple' with a list as one of its items.
define_a_tuple = (1, 1, [3,4])

#Items with same value have the same id.
id(define_a_tuple[0]) == id(define_a_tuple[1])


#Items with different value have different id.
id(define_a_tuple[0]) == id(define_a_tuple[2])

id(define_a_tuple[0])

id(define_a_tuple[2])

define_a_tuple.append(11)
cannott append an item to a tuple
cannot append an item to a tuple

We can’t append an item to a tuple, which is why you’re getting an error like this. It is for this reason why a tuple is referred to as immutable. However, you can always perform the following:

define_a_tuple[2].append(5)
define_a_tuple

As a result, you’ll be able to alter the original tuple. So how is it that the tuple is still referred to as immutable?

Even though you added 11, the id of the list within the tuple remains the same.

id(define_a_tuple[2])

Value access in Tuples

Use the square brackets for slicing along with the index or indices to get the value accessible at that index in a tuple.

define_tup_1 = ('first', 'second', 200, 400);
define_tup_2 = (3, 5, 6, 7, 8, 9, 10 );
print(define_tup_1[0])
print(define_tup_2[1:5])

For instance, when the above code is run, the following is the result:

Value access in Tuples
Value access in Tuples

Negative Indexing

Python sequences support negative indexing. For instance, the index of -1 denotes the last item, the index of -2 the second last item, and so on.

# Negative indexing while accessing elements in a tuple
define_tuple = ('p', 'e', 'r', 'm', 'i', 't')

# how to output: 't'
print(define_tuple[-1])

# how to output: 'p'
print(define_tuple[-6])
Negative Indexing
Negative Indexing

Value update in Tuples

Tuple elements are immutable, which means you can’t update or change their values. However, as seen in the following example, you can use parts of existing tuples to generate new ones.

define_tup_1 = (12, 34.56)
define_tup_2 = ('abc', 'xyz')

# Following action is not valid for tuples
# define_tup_1[0] = 100

# So let's create a new tuple as follows
define_tup_3 = define_tup_1 + define_tup_2
print(define_tup_3)
Value update in Tuples
Value update in Tuples

Removing Tuple Elements

Individual tuple elements cannot be removed. But, of course, there’s nothing wrong with putting together another tuple without the unwanted components.

Use the del statement to precisely remove a whole tuple. For instance,

define_tup_1 = ('first', 'second', 200, 400)
print(define_tup_1)
del define_tup_1
print("After deleting define_tup_1 : ")
print(define_tup_1)
Removing Tuple Elements
Removing Tuple Elements

As a result, you’ll get the following outcome. There is an error triggered because the tuple does not exist after del define_tup_1.

There are no enclosing delimiters

Any comma-separated group of numerous objects written without distinguishing symbols, such as brackets for lists, parentheses for tuples, and so on, defaults to tuples, as seen in these short examples.

print( 'abc', -4.24e93, 18+6.6j, 'xyz')
x, y = 1, 2
print ("Value of x , y : ", x,y)

When the above code is run, the following result is obtained:

no enclosing delimiters
no enclosing delimiters

Tuple has several advantages over a list

  • Because tuples and lists are so similar, they’re utilized in similar scenarios. However, there are some advantages to using a tuple rather than a list. The following are some of the most significant benefits:
  • We use tuples for heterogeneous (different) data types, while we use lists for homogeneous (similar) data types.
  • Iterating over a tuple is faster than iterating through a list because tuples are immutable. As a result, there is a minor performance boost.
  • Tuples containing immutable elements can be used as a dictionary’s key. It is not feasible with lists.
    If you have non-changing data, implementing it as a tuple will ensure that it remains write-protected.

Example of Using cmp()

# program illusrating how to use # cmp()

define_tuple1 = ('python', 'codeunderscored')
define_tuple2 = ('coder', 1)

if (cmp(define_tuple1, define_tuple2) != 0):
  	# cmp() returns 0 if matched, 1 when not tuple1
	# is longer and -1 when tuple1 is shoter
	print('Not the same')
  
else:
  
  print('Same')
  

Example of Using cmp()
Example of Using cmp()

Applications of Tuples

Tuples are frequently employed as a kind of modification resistance. Tuples can be used to write-protect data because they are immutable.

When it comes to iterating over a tuple, we see a significant performance boost compared to lists. It is more noticeable when the tuple size is large. We can observe that iterating tuples is significantly faster than iterating lists using Python’s timeit function.

An immutable key exists in the dictionary data structure. As a result, tuples can be utilized as a dictionary key.

Tuples can be used to organize data that is related. An entry in a database table, for example, can be joined together and stored in a tuple.

Conclusion

You’ve completed this tuple tutorial! You learned more about Python tuples, how to initialize them, the most frequent operations you can do on them to modify them, and the most popular ways you can use to get more information from these Python data structures along the way. You also learned that you could assign multiple values to tuples.

Some tuples (those containing only immutable objects such as strings, etc.) are immutable, while others (those containing one or more mutable objects such as lists, etc.) are mutable. It is a more detailed article on the subject. However, this is a contentious topic among Pythonistas, and you will need more background knowledge to comprehend it fully. So, for the time being, let us state that tuples are immutable in general.

Because tuples are immutable, you can’t add elements to them. Tuples have no append() or extend() methods, and you can’t remove elements from them due to their immutability. Tuples don’t have remove() or pop() methods, but you can discover features in them because they don’t affect the tuple.

You may also use the in operator to see if a tuple element exists.

Use a tuple instead of a list if you’re defining a constant set of values that you’re just going to cycle through. It will be faster and safer than working with lists because tuples contain “write-protected” data.

Thank you for taking the time to read this. Would you mind letting us know if you have any suggestions?

You may also like

Leave a Comment

This website uses cookies to improve your experience. We'll assume you're ok with this, but you can opt-out if you wish. Accept Read More