An Introduction to Python Tuple

Let us learn about python tuple in detail.

Photo by Toa Heftiba on Unsplash

Python Tuple:

Tuple is a Python data structure which are ordered and immutable.Python tuples are written within parentheses. Tuples are immutable, and usually contain a heterogeneous sequence of elements that are accessed via unpacking or indexing.

Image by Author
  • Creating a tuple:
  1. To create a tuple with a single item, we have to add a trailing comma. a, or (a,)

https://gist.github.com/IndhumathyChelliah/ceaa627f0fd45d91eaa3d9a68cc5c6f9

Singleton tuple can be created with trailing comma, with or without parentheses.

https://gist.github.com/IndhumathyChelliah/f24f284364f12d5bb83b40b8b1a2df2d

2. Using tuple constructor:

  • tuple()

https://gist.github.com/IndhumathyChelliah/5c8f52f12e3f2a5b43fc2858d4f6e92a

  • tuple(iterable)

iterable can be a sequence, a container that supports iteration, or an iterator object.

  • iterable can be sequence like list, string.

https://gist.github.com/IndhumathyChelliah/ce878ff3bffe9283f6457e5a5bfb00b1

  • iterable can be containers that support iteration like a set,dict

https://gist.github.com/IndhumathyChelliah/2672fdb85a4a6dd51f4598d8f2e41cdc

  • iterable can contain an iterator object also.

https://gist.github.com/IndhumathyChelliah/88bf08c7edede7aab962f3890fedd423

3. Tuple can contain different data types also. It is written within parentheses.

https://gist.github.com/IndhumathyChelliah/40dd7451f4a4c1f7f8a93bb64f342a41

4. Creating an empty tuple.

https://gist.github.com/IndhumathyChelliah/4565a904da7ad32412f497c3adb1f951

5.Separating items with commas: a, b, c or (a, b, c)

We can create tuple without parentheses also. Actually, the comma makes a tuple. Parentheses are optional except in empty tuple or when they are needed to avoid syntactic ambiguity.

Example: 
f(a,b,c) — function call with three arguments
f((a,b,c))-function call with one argument as 3-tuple. 3-tuple means tuple having 3 elements.

https://gist.github.com/IndhumathyChelliah/c8f7bf625fc8e59f13ae98e6bc508472

6. Creating a nested tuple

https://gist.github.com/IndhumathyChelliah/218fecacfb7bc3c1a6eb93eb6e76bcdd


  • Tuples are immutable

Tuples do not support item assignment. It will raise TypeError.

https://gist.github.com/IndhumathyChelliah/05331c4ba6ac0627642a623f21df83c1


  • Tuple packing, Tuple unpacking:

Tuple packing:

t=1,2,3,’hello’

The values 1,2,3,’hello’ are packed together in a tuple. This is called tuple packing.

Tuple unpacking:

Tuple unpacking is assigning elements in the tuple to variable in a single assignment statement.
Tuple unpacking requires that there are as many variables on the left side of the equals sign as there are elements in the tuple.
Otherwise, it will raise ValueError.

https://gist.github.com/IndhumathyChelliah/a668b57a88eaf0d8f64031dafa25d601


  • Accessing tuple elements:
  1. We can access tuple elements by using index numbers inside square brackets. The first element starts at index 0.

https://gist.github.com/IndhumathyChelliah/e0119df6da55810267b3904140482cca

2. Negative Indexing.

We can access using a negative index also. Negative indexing starts from the end. -1 refers to last element.

https://gist.github.com/IndhumathyChelliah/ad86d747f176956c03c354f1e7e01aae


  • Slicing (Range Of Indexes):

We can specify a range of indexes. Returns new tuple containing specified elements.

s[i:j:k] — slice of s from i to j with step k

t[1:3] – Returns a tuple containing element at first and second index.
t[1:] – Returns a tuple containing an element from the first index till the end of the tuple
t[:] – Returns a tuple containing all elements
t[:4] – Returns tuple containing elements from starting till the third index.

https://gist.github.com/IndhumathyChelliah/1d2ca666db53f6d9ae82e395521ecfc3

Slicing using step argument:

https://gist.github.com/IndhumathyChelliah/155310517ab0d323b8911c5fb93fc258


  • Modifying tuple:

A tuple is immutable. So we can’t add or remove elements from the tuple. We can only delete tuple.

But we can add items by converting tuple to list and then add items and convert back to a tuple.

https://gist.github.com/IndhumathyChelliah/8bec2924f7e1e161c06a196cc84cde65

If a tuple contains mutable data types like list, we can modify that list.

https://gist.github.com/IndhumathyChelliah/f4b55561ee6e729e32e5951504a1931c

  • Deleting tuple:

we can delete tuple by using del keyword.

https://gist.github.com/IndhumathyChelliah/001227725988e8f2213b2306fdd5c61d


  • Joining tuples:

We can combine two tuples using + operator.

https://gist.github.com/IndhumathyChelliah/8708dbb930eb093a141b22344b9785f3

We can repeat the elements in tuple using * operator

https://gist.github.com/IndhumathyChelliah/de703274aeb16aac5bf2be1d257181de


  • Tuple Built-in Methods:
  1. index()
  2. count()

index():

Returns the index of the specified element in the tuple. If the element is not in tuple means, it will raise a ValueError. If the specified value occurs more than one-time means, it will return the index of the first occurrence.

t.index(x,start,end)

x-element to be searched
start,end-The optional arguments start and end are interpreted as in the slice notation and are used to limit the search to a particular subsequence of the tuple.

https://gist.github.com/IndhumathyChelliah/9a033bb80fd1c3e6d60464f5c2b2d57c

count(): Returns the count of the specified value in the tuple.

https://gist.github.com/IndhumathyChelliah/f3254195db6743cb06a67f6a8646c691


  • Membership Test:

We can check whether an item is present in the tuple or not by using in keyword.

https://gist.github.com/IndhumathyChelliah/bc600fc15cf6ed0a31112df540a8ce6a


  • Comparison Operations:

Tuples compare lexicographically using a comparison of corresponding elements.

Lexicographic order is the way of ordering of words based on the alphabetical order of their component letters.. In case of strings for example consider ABC then all its permutations in lexicographical order will be “ABC, ACB, BAC, BCA, CAB, CBA”

When applied to numbers, lexicographic order is increasing numerical order, i.e. increasing numerical order (numbers read left to right).

1.Equality operation on tuples:

For two tuples to compare equal, they must be of the same type, have the same length, and each pair of corresponding elements must compare equal (for example, [1,2] == (1,2) is false because the type is not the same).

https://gist.github.com/IndhumathyChelliah/1957e8900aeb8812da645301bc33a724

2. Order Comparison

Order comparisons between tuples check for the first unequal element in the set. (for example, [1,2,x] <= [1,2,y] has the same value as x <= y). If a corresponding element does not exist, the shorter collection is ordered first (for example, [1,2] < [1,2,3] is true).

https://gist.github.com/IndhumathyChelliah/0f120cd20054aa05055cd4f095b0ee75

Order comparisons (<,>,≤,≥) between tuple and other collections raise TypeError.

https://gist.github.com/IndhumathyChelliah/4680035880237f3060ce28b3851bd686


  • Sorting tuple:

sorted()
sorted() function will sort tuple and return a new sorted list. It won’t modify the original tuple. By default, it will sort in ascending order.

sorted(iterable,key=None,reverse=False)

Return Type: List

https://gist.github.com/IndhumathyChelliah/c320d5597803439113a999880c74887d

Sorting tuple in descending order

If the reverse is set to True, it will sort the tuple in descending order.

https://gist.github.com/IndhumathyChelliah/743db2d06c6c431304fefd5328694dcf

Sorting tuple using the key parameters.

We can also sort tuple based on the function specified in the key parameter. By default, the sorted function will sort a list of tuples based on the first element. Here we mentioned a user-defined function to take the second element. So, now sorted function sort the list of tuples based on the second element

https://gist.github.com/IndhumathyChelliah/6cbee4066ac2b1e620c3fce9b0eefc19


Tuple Built-in Functions:

  1. len()

2. min()

3. max()

4. sum()

len(): Returns the number of elements in the tuple.

https://gist.github.com/IndhumathyChelliah/22a9434990c37d95a4a0b090a3774e5f

min(): Returns the smallest element in the tuple.

max(): Returns the largest element in the tuple.

sum(): Returns the sum of all elements in the tuple.

https://gist.github.com/IndhumathyChelliah/8e073538920e37de0fcaec5501636119

  • hash():
    hash() is supported in immutable sequence types- tuples.
    This support allows immutable sequences, such as tuple instances, to be used as dict keys and stored in set and frozenset instances.
    Attempting to hash an immutable sequence that contains unhashable values will result in TypeError.

https://gist.github.com/IndhumathyChelliah/160aa7128685fcb00c80b19c8e3ab65c


  • Iterating through tuple:

We can use for loop to iterate through tuple.

https://gist.github.com/IndhumathyChelliah/cd9abf7ceaba8e4cb73abd2147ea56f4


My other blogs on Python data structures

An Introduction to Python List

String Methods in Python

An Introduction to Python Set

An Introduction to Python Dictionary


Resources:

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s