Single Element Tuples
Disclaimer: This post has been translated to English using a machine translation model. Please, let me know if you find any mistakes.
If in Python we want to create a list with a single element, we simply write the element between square brackets, for example:
list = [1]type(list)
list
However, with tuples we cannot write an element within parentheses
tupla = (1)type(tupla)
int
As we can see, Python interprets it as an integer, not as a tuple. To solve this, a comma is added after the element, for example:
tupla = (1,)type(tupla)
tuple
What is this for? When we have a function that returns several parameters, what it is actually returning is a tuple. So, it may happen that we have a code that calls a function, checks the length of the returned tuple, and processes each element of the tuple. Let's look at an example
def return_tuple():return 1, 2, 3def process_tuple():tuple = return_tuple()for i in tuple:print(i)process_tuple()
123
But, what happens in this example if the function doesn't return a tuple? We would get an error
def return_int():return 1def process_tuple():tuple = return_int()for i in tuple:print(i)process_tuple()
---------------------------------------------------------------------------TypeError Traceback (most recent call last)Cell In[5], line 96 for i in tuple:7 print(i)----> 9 process_tuple()Cell In[5], line 6, in process_tuple()4 def process_tuple():5 tuple = return_int()----> 6 for i in tuple:7 print(i)TypeError: 'int' object is not iterable
We get an error because Python tries to iterate through what the function returns, but since it returns an integer it can't iterate through it. We have two ways to solve this, one is that the processing function checks if a tuple has been returned and in that case processes it, another is that the function that returns values always returns a tuple, even if it is a single element.
def return_int():return 1,def process_tuple():tuple = return_int()for i in tuple:print(i)process_tuple()
1
As we see, in the return_int
function a ,
has been placed at the end of the return
, so it is returning a tuple with a single element, which is why the process_tuple
function will not give an error.