Python Tuples Complete Tutorial

In this section, we will learn what Tuples are and how to use them in Python.

Note: we’re also assuming you’re familiar with Python List object.

What is Tuple in Python?

The Python Tuple object is a type of object that is capable of holding other values (other objects) as its elements.

Basically, a tuple is a container for other elements, just like the List object.

But the main difference between a List object and a Tuple is that Tuples only take elements when they are being initialized, while lists are capable of taking more elements after their initialization!

So Tuples are static! You can just assign values to it once and after that there’s no way of adding or removing the current values of a tuple object.

Python How to Create a Tuple: Declaring a Tuple in Python

In order to create a tuple object, we use a pair of parentheses and inside that we put the elements of the target Tuple object.

Example:

tupVariable = (value1, value2, valueN)

Python Tuple: Access Tuple Elements (Items)

First of all, you should know that each element in a tuple object has an index number just like a list object.

The first element in a tuple object is at the index 0, the second one is at index 1 and so on…

Now, in order to access the elements of a tuple object we can use a pair of brackets `[]` after the name of the target tuple object and pass the index number of each element that we want to get it from the tuple object.

Example: accessing python tuple elements

tup1 = ("Ellen","Jack","Omid","Elon")

print(tup1[0])
print(tup1[1])
print(tup1[2])
print("***********")
for num in range(len(tup1)):
    print(tup1[num])

Output:

Ellen

Jack

Omid

***********

Ellen

Jack

Omid

Elon

Python tuple() Function

Another way of creating a tuple object is by using the `tuple()` function.

This function takes an iterable object as its argument and then uses the elements of that iterable object and creates a new tuple from those elements.

Note: the iterable object could be a string value, a list object, another tuple, etc.

Example: creating tuples with python tuple() function

fullName = "John Doe"

tup1 = tuple(fullName)

list1 = [1,2,3,4,5,6]

tup2 = tuple(list1)

print(tup1)

print(tup2)

Output:

('J', 'o', 'h', 'n', ' ', 'D', 'o', 'e')

(1, 2, 3, 4, 5, 6)

Python Tuple Length

If we want to know how many elements a tuple object has, we can use the `len()` function.

Simply pass the target tuple object as the argument of this function and it will return the size or the number of elements that tuple object has.

Example: python length of tuple

tup1 = ("Ellen","Jack","Omid","Elon")

size = len(tup1)

print(f"The size of the tuple object is: {size}")

Output:

The size of the tuple object is: 4

Python Tuple with Single Element

A tuple object can have a single element as well! In that case, we need to put a comma after the element! Otherwise, the execution engine considers the target value as something other than tuple!

Example: creating single element tuple in python

tupVar = ("John",) #This is the correct way of creating a single element Tuple object.

wrongTuple = ("John") #This is basically just a string value

anotherWrongTuple = (10) # This is just an integer value!

print(type(tupVar))

print(type(wrongTuple))

print(type(anotherWrongTuple))

Output:

<class 'tuple'>

<class 'str'>

<class 'int'>

Python Print Tuple

The simplest method of printing a tuple object to the output string is to use the `print()` function and pass the tuple object directly as its argument.

That way, the tuple object will be printed to the output stream.

But other than that, we can use the for loop and take the entire elements of a tuple object and print them on the output stream one at a time.

Example: print tuple in python

tup1 = ("Ellen","Jack","Omid","Elon")

for element in tup1:
    print(element)

Output:

Ellen

Jack

Omid

Elon

Python Tuple to String

In order to convert a tuple object into a string, all we need to do is to pass the target tuple object into the `str()` function, which will produce a string from the elements of a tuple object.

Note: the str() function takes an iterable object as its argument! So other than a tuple object, we can use any other iterable objects as the argument of this function and as a result we will get a string from the elements of that target object.

Also, there are other methods that could be used to create a string value from a tuple object. For example, using a `for` loop to loop through the entire elements of a tuple and then combine those elements into a variable, but the simplest method is to directly use the `str()` function.

Note: the use of `str()` function will add the parentheses as well as the commas that are used to separate the elements of a tuple object. So if you don’t want to have those characters as part of the created string, you might want to use other methods like `for` loop, for example.

Example: converting tuple to string

tup1 = ("Ellen","Jack","Omid","Elon")

string = str(tup1)

print(type(string))

print(string)

Output:

<class 'str'>

('Ellen', 'Jack', 'Omid', 'Elon')

List of Tuples in Python

Tuples are objects like any other object in Python. That means we can use a tuple object and set it as the element of a list object as well.

Example: list of tuples python

list1 = [

("Omid","Jack","John","Ellen","Elon"),

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

(True,False,True),

({"name":"John","lastName":"Doe"},{"name":"Omid","lastName":"Dehghan"})

]

print(list1[3][0]["name"])

print(list1[3][1]["name"])

Output:

John

Omid

The use of 3 pair of brackets in each of the calls to the `print()` function might be confusing at first, so let’s break the first call down and see what happened there:

Take a look at this statement:

list1[3][0]["name"]

This is basically 3 independent statements combined into one!

The first statement is:

list1[3]

The statement above is saying bring a reference to the element of the `list1` object that has the index number 3.

Now the next statement is:

[0]

This statement is saying after getting the result of the `list1[3]` statement, move into its elements and bring back the first element.

Now in the last statement:

[“name”]

This statement is telling the execution engine that from the result that it got by running the `[0]` statement (Which is a dictionary), it should now get the value assigned to the `name` property.

That’s how we got the value “John” for the first call to the `print()` function and got the value `Omid` from the second call to the `print()` function.

Tuple Index Out of Range

The index number of a tuple object is equal to the size of that tuple -1 (because the first element is at the index number 0). So as long as we use index numbers within the range, there’s no problem and the execution engine will return the value we want at the specified index.

But the moment we use an index number that the target tuple doesn’t have, we will get an error that is known as “Index Out of Range”.

Example: throwing and handling tuple index out of range in python

tupVar = ("Omid","Jack","John","Ellen","Elon")

print(tupVar[10])

Output:

IndexError: tuple index out of range

As you can see, the tuple object of this example has only 5 elements and so the indexes of this tuple is ranged from 0 to 4. Now because we used the value 10 as the index number for this tuple object, we got the error you see in the example above.

Python List vs Tuple

As mentioned before, list and tuple objects both are container objects, meaning they are capable of storing multiple values as their elements.

But their difference is that the tuple object is only capable of taking values while being initialized and after that there’s no way of adding or removing the elements of a tuple object.

On the other hand, a List object is capable of taking more values at later times or remove elements from its body if needed.

Python Convert List to Tuples

We mentioned that the `tuple()` function is capable of taking an iterable object and create a tuple object using the elements of that iterable object.

This means we can pass a list object as the argument of this function and take back a tuple object with the elements of the specified list.

That’s how we can convert a list into a tuple object.

Example: converting list to tuples in python

list1 = ["Omid","Jack","John","Ellen","Elon"]

tupVar = tuple(list1)

print(tupVar)

Output:

('Omid', 'Jack', 'John', 'Ellen', 'Elon')

Python Tuple: Check if Item Exist

Using the combination of `if` statement and the `in` and `not in` operators, we can check the elements of a tuple object and see if it has a specific value as part of its elements or not.

Example: checking if item exist in python tuple

tupVar = ("Omid","Jack","John","Ellen","Elon")

if "Elon" in tupVar:
    print("Yes, the target tuple object has the value Elon as part of its elements")

Output:

Yes, the target tuple object has the value Elon as part of its elements
Facebook
Twitter
Pinterest
LinkedIn

Top Technologies