What Are Tuples in Python? And Everything You Should Know About Them. | 1
|

What Are Tuples in Python? And Everything You Should Know About Them.

Tuples are an ordered, immutable collection type in Python. That is, elements in Tuple are not modifiable, and neither are their positions.

Tuples are also indexed. This means we can access the elements of a Tuple using their positional index (starts with 0)

Tuples allow duplicates and different data types as their elements. Hence, it’s a flexible array-like alternative to storing data in Python with better performance than lists.

This post is about the basics of Tuples and the methods we can use on Tuples.

What is Tuples in Python?

Tuples are one of the four (Lists, Sets, Dictionary) data types to store a collection of items. Also, elements in Tuples are ordered and indexed. This array-like object type does not allow for modifications. Yet they allow duplicates.

These properties make Tuples more flexible than sets that don’t allow duplicates. But Tuples are a bit more rigid than lists that permit modification.

Related: How to Learn and Improve Your Python Coding Skills With Free Resources?

You can create a Tuple by specifying elements inside parenthesis.

heros=("Spider Man", "Captain America", "Iron Man", "Black Panther", "Thor", "Hulk")
Python

You can have as many items as you want inside a Tuple. Yet, if there’s only one item, there has to be a trailing comma before you close the parenthesis.

villan = ("Thanos",)
Python

You could also use a Tuple constructor to create them. Tuple constructors are helpful when you need to create Tuples programmatically or convert them from a list or set.

heros=tuple(["Spider Man", "Captain America", "Iron Man", "Black Panther", "Thor", "Hulk"])
Python

Tuples can have more than one type of element. It doesn’t have to be the same type.

hero_one = (“Spider Man”, 16, True, 110.5)
Python

How to access tuple elements?

Python tuples are ordered and indexed, which makes accessing elements easier. We can get a single item by its index or many of them in a range of indexes.

Indexing in Python starts with zero. The first element in the tuple has an index of 0. To access the 5th element in we must use index 4.

heros=("Spider Man", "Captain America", "Iron Man", "Black Panther", "Thor", "Hulk")

# Access the first element in a tuple
print(heros[0])
>>> 'Spider Man'

# Access the 5th elemen tin the heros tuple
print(heros[5])
>>>  'Thor'
Python

You can also specify a starting and ending index to select elements in a range of indexes. When you do a range selection on a Tuple, the return type is also a Tuple.

print(heros[3:5])
>>> ('Black Panther', 'Thor')

type(heros[3:5])
>>> <class 'tuple'>
Python

Sometimes you may want to select elements in steps. For instance, every other element in a Tuple. In that case, you can specify a range and the steps.

heros[1:5:2]
>>> ('Captain America', 'Black Panther')
Python

Tuples in Python support negative indexes. Thus to select the last element, you can use the index -1. For the third element from the last, you can use -3.

heros[-1]
>>> 'Hulk'
Python

You could also use index range selection with negative indexes. For instance, you can use the negative index -1 to get every other element in a Tuple with no reference to the length of the Tuple.

heros[0:-1:2]
>>> ('Spider Man', 'Iron Man', 'Thor')
Python

Finding the index of an element in a Tuple

You may want to find the position (or the index) of an element inside a Tuple. You can use the index method on a tuple with the element as the argument to find its location.

heros.index('Hulk')
>>> 5
Python

Counting elements on a Tuple

Frequently we need to count the occurrence of a specific element in a tuple. In Python, you don’t have to loop through the elements and increment a variable to count them.

You can use the count method on a tuple with an element as its argument. The count method will return the number of times the element appeared in the list.

my_tuple = ('a', 'b', 'c', 'b', 'd', 'a', 'b', 'f')
print(my_tuple.count('a'))
>>> 2
print(my_tuple.count('b'))
>>> 3
print(my_tuple.count('f'))
>>> 1
Python

Modifying or Updating a Tuple

Tuples are immutable. That is, you can not edit the elements of a Tuple after you’ve created it.

You must use a list if you still want to edit tuple items.

If lists are incompatible with your code, you may convert them back to tuples after you change them.

For instance, you can append an item to a tuple as follows.

heros_list = list(heros)
heros_list.append('Black Widow')
heros = tuple(heros_list)
print(heros)
>>> ('Spider Man', 'Captain America', 'Iron Man', 'Black Panther', 'Thor', 'Hulk', 'Black Widow')
Python

Deconstructing tuple elements.

Deconstructing or unpacking tuples is a clever way of accessing elements with less code. For instance, let’s say we have a tuple whose,
– the first element is the name of our hero;
– the second element is the age of our hero;
– the third element is if our hero is part of the Avengers and;
– finally, our hero’s weight.

Suppose we want to assign these values to individual variables; we can use tuple deconstructors.

name, age, is_avenger, weight = ("Spider Man", 16, True, 95.8)
print(name)
>>> Spider Man
print(age)
>>> 16
print(is_avenger)
>>> True
print(weight)
>>> 95.8
Python

As you can see, deconstructors are elegant and concise. These assignments would have taken four lines. But with deconstructors, we’ve assigned tuple elements to variables in a single line.

The ordered property of Tuples allows variable assignment with deconstructors.

If you don’t want all the elements of a Tuple unpacked, you can use an asterisk in the deconstructor assignment.

For instance, if we’re interested in a hero’s name and age, then we could do something like this. A variable with an asterisk will put all the remaining elements into this bucket. This would be a tuple too.

name, age, *other_hero_properties = ("Spider Man", 16, True, 95.8)
print(name)
>>> Spider Man
print(age)
>>> 16
print(other_hero_properties)
>>> [True, 95.8]
Python

The asterisk in the tuple doesn’t have to be at the end. We can also take the first (or the first few) and the last (or the last few) and everything in the middle into three separate variables.

name, *all_other_hero_properties, weight = ("Spider Man", 16, True, 95.8)
print(name)
>>> Spider Man
print(weight)
>>> 95.8
print(all_other_hero_properties)
[16, True]
Python

Loop through tuple elements

Tuples are a type of iterable in Python. This means you can loop through their elements with ‘for’ or ‘while’ loops. Since tuples are indexed, you can also loop through their index.

# Loop through heros
for hero in heros:
    print(hero)


# Loop through heros using tuple indexes.
for i in range(len(heros)):
    hero = heros[i]
    print(hero)
Python

You can also loop through the elements of a tuple until a certain condition is met. You can use the while loop to do so.

i = 0
while i < len(heros) - 5:
    i += 1

    print(heros[i])
Python

You can find more examples of iterating over tuple elements.

Concatenating tuples.

Tuples in Python are immutable. Yet, two or more tuples can be joined together to form a new tuple.

marvel_heros = ("Spider Man", "Captain America", "Iron Man")

dc_heros = ("Superman", "Batman", "Wonder Woman")

heros = marvel_heros + dc_heros

print(heros)

>>> ('Spider Man', 'Captain America', 'Iron Man', 'Superman', 'Batman', 'Wonder Woman')
Python

Thanks for the read, friend. It seems you and I have lots of common interests. Say Hi to me on LinkedIn, Twitter, and Medium.

Not a Medium member yet? Please use this link to become a member because I earn a commission for referring at no extra cost for you.

Similar Posts