Welcome to this tutorial on How to Create a Python Tuple, which is used to store multiple Elements into a single Python Variable.
Python Tuples are Ordered, Immutable and allow for Duplicates. The easiest way to recognize a Python Tuple is by its usage of Parentheses ( ).
Tuples are one of 4 built-in data types in Python, that are used to store collections of data. The other 3 Python Iterables (Collection Data Types) are Lists, Sets, and Dictionaries, each with their own different qualities and usages.
NOTE: This tutorial requires that Python is already installed, as well as an IDE (Integrated Development Environment), such as PyCharm. It’s also recommended that you have a basic understanding of How to Use Python if this is your first time learning Python, as well as Python Variables and Data Types.
With that said, let’s get started with this free Python Tuple tutorial.
How to Create a Tuple in Python
A Python Tuple is created using Parentheses ( ), in which its Elements are stored. A Tuple is assigned to a Variable name as follows:
Tuple_Variable_Name = (Tuple_Element0, Tuple_Element1, Tuple_Element2, Tuple_Element3)
Python Tuple Example:
Here is a Python Tuple that contains three fruits as its Elements, in the form of Strings, assigned as a Variable named “fruit_tuple”:
fruit_tuple = ("apple", "orange", "banana")
print(fruit_tuple)
#>> ('apple', 'orange', 'banana')
We then print out the “fruit_tuple” Variable by using the “print(fruit_tuple)” statement. Python outputs (‘apple’, ‘orange’, ‘banana’) which is our Tuple of fruits.
Parentheses ( ) are NOT Required when creating a Python Tuple
A Tuple can also be created without the use of Parentheses ( ).
fruit_tuple = "apple", "orange", "banana"
print(fruit_tuple)
#>> ('apple', 'orange', 'banana')
Even though we did not use the parentheses ( ) to create the Tuple, Python still creates a Tuple in the output, when using the Print Statement.
Tuples require at least 2 or more Elements
A Tuple requires at least 2 Elements or more in order for Python to recognize it as a Tuple.
If there is only one Element of “apple” in a Tuple, it will become a String Data Type instead of a Tuple. We can test this using the “type()” Function:
fruit_tuple = ("apple")
print(fruit_tuple)
print(type(fruit_tuple)) # Calling the “fruit_tuple” Variable inside of the type() Function
#>> apple
#>> <class ‘str’> # The apple is the only Element, therefore it defaults to its Data Type of String
The “apple” is the only Element, therefore it defaults to its Data Type of String and not a Tuple in the output.
How to Create a Tuple with a Single Element, using an extra Comma
We can however get around this and create a Tuple with a Single Element, by putting a comma after the Element of “apple”. This isn’t ideal and a bit of a “hack”, but it does work as intended.
fruit_tuple = ("apple",) # Adding a comma after the only Element in the Tuple
print(fruit_tuple)
print(type(fruit_tuple)) # Calling the “fruit_tuple” Variable inside of the type() Function
#>> apple
#>> <class ‘tuple’> # The apple element is now a Tuple and not a String
The “apple” Element is now Tuple and not a String as before, thanks to the extra comma.
Python Tuples don’t require any Elements
While Python Tuples do require 2 more more Elements, they can actually be completely empty, requiring no Elements at all, to still be seen as a Tuple Data Type by Python:
fruit_tuple = ()
print(fruit_tuple)
print(type(fruit_tuple)) # Calling the “fruit_tuple” Variable inside of the type() Function
#>> ()
#>> <class 'tuple'> # Confirmation that this is in fact a Tuple
Again, we see that this still remains an empty Tuple, even with no Elements.
Data Types that a Python Tuple can contain
Python Tuples can contain any of the following Data Types as Elements, both individually or mixed within a single Tuple:
- Integers (int) – Whole numbers such as: 1, 14, 576.
- Floating Point (float) – Decimal values such as: 1.24, 5.6 and Fractional Values such as 1/2, 9/6.
- Strings (str) – Sequence of Characters such as: “I love Python”, “this course is great”, “year 3000”.
- Booleans (bool) – Logical values representing: TRUE or FALSE.
For example, we are able to create the following mixed Data Type Tuple:
mixed_tuple = (14, 365.34, "welcome", True) #int, float, string, bool
print(mixed_tuple)
#>> (14, 365.34, "welcome", True)
All four Data Types, including the int, float, string and bool were successfully output within the Tuple.
Python Iterables that can be stored within a Tuple
Python Tuple aren’t limited to only storing single Data Types either. Tuple are able to store other Python Iterables (Collection Data Types) within them, including Lists, Sets, Dictionaries and even a Tuple within a Tuple.
Here is an example of a Python Tuple with a Tuple, Set, Dictionary and a List stored as its Elements:
mixed_iterable_tuple = (("apple", "orange"), {"apple", "orange"}, {"a": 1, "b": 2}, ["apple", "orange"]) #tuple, set, dictionary, list
print(mixed_iterable_tuple)
#>> (('apple', 'orange'), {'apple', 'orange'}, {'a': 1, 'b': 2}, ['apple', 'orange'])
Using the Print Statement to output the results, we can see that Python successfully accepted the other Iterables as Elements within the Tuple.
How to Check for a Python Tuple using the type() Function
If you are unsure if a variable or output is in fact a Tuple, you can easily check this using the type() Function:
fruit_tuple = ("apple", "orange", "banana")
print(fruit_tuple)
print(type(fruit_tuple)) # type() Function within Print Statement
#>> ('apple', 'orange', 'banana')
#>> <class 'tuple'> # Confirmation that this is a Tuple
Python outputs <class ‘tuple’>, which confirm to us that the Variable is indeed a Tuple.
How to Check the Length of a Python Tuple using len() Function
The length of a Python Tuple can be defined using the len() Function:
fruit_tuple = ("apple", "orange", "banana")
print(len(fruit_tuple))
#>> 3
This outputs the number 3 (int), which tells us how many Elements we have in our Python Tuple.
Python Tuple are Ordered, Immutable & Allow Duplicates
A Python Tuple is Ordered, Immutable, and allows for Duplicate Elementss. Tuples are similar to Lists, except that a Tuple cannot be changed after its creation, while a List can.
Python Tuple are Ordered
Python Tuple are Ordered and thus the Elements within a Tuple have a defined order.
Being Ordered means that no matter how many times a Python Tuple is output by Python (such as using a Print Statement), the order of the Elements in the Tuple will not change:
# FIRST RUN
fruit_tuple = ("apple", "orange", "banana")
print(fruit_tuple)
#>> ('apple', 'banana', 'orange')
# SECOND RUN
fruit_tuple = ("apple", "orange", "banana")
print(fruit_tuple)
#>> ('apple', 'banana', 'orange')
# THIRD RUN
fruit_tuple = ("apple", "orange", "banana")
print(fruit_tuple)
#>> ('apple', 'banana', 'orange')
Each output run will keep the Elements of the Tuple in the exact same defined order of the original Tuple, unlike Sets (set) which will randomize the order every time.
Python Tuple are Immutable
Python Tuples are also Immutable, meaning that we cannot change, add and remove Elements in a Tuple, after it has been created.
Python Tuple Methods
Therefore, the only Methods available to a Tuple are the following:
- count() : Returns the number of times a specified value occurs in a Tuple
- index() : Returns the Index of the FIRST element with the specified value
If we try to add a “kiwi” to the Tuple of fruits by using the .append() function, we will get an error:
fruit_tuple = ("apple", "orange", "banana")
fruit_tuple.append('kiwi') # Trying to add kiwi into the Tuple item Elements
print(fruit_tuple)
#>> AttributeError: 'tuple' object has no attribute 'append'
As Tuples are Immutable, Python tells us that the append attribute cannot be used in the error message AttributeError: ‘tuple’ object has no attribute ‘append’.
While we cannot natively add or change a Tuple after it has been created, there are a few workarounds that are available.
Python Tuple Allow Duplicates
Python Tuples also allow for duplicate Elements:
fruit_tuple = ("apple", "orange", "banana", "apple")
print(fruit_tuple)
#>> ('apple', 'orange', 'banana', "apple)
Here we can see that we have two copies of the “apple” Element.
Python Tuple Conclusion
I hope you enjoyed this tutorial on how to create a Python Tuple. This should give you the starting knowledge you need to easily create Tuples in Python for your code or project.
Python Tuple Summary
Here is a summary of what we learnt when creating a Python Tuple:
- Python Tuples use, but do not require Parentheses ( ).
- Python Tuples must be created using Two or more Elements.
- Python Tuples can be empty with no Elements at all.
- Python Tuples can contain Integer (int), Floating Point (float), Strings (str) and Booleans (bool) Data Types as their Elements.
- Python Tuples can contain other Python Iterables, such as List, Sets, Dictionaries and even other Tuples as their Elements.
- The type() Function can be used to check if a Variable is a Tuple.
- The len() Function can be used to check the Length of a Tuple.
- Python Tuples are Ordered, meaning that the Elements will always have a defined order that will not change.
- Python Tuples are Immutable, meaning that Elements cannot be changed, added, removed, sorted, reversed using Methods.
- Python Tuples allow for Duplicate Elements, meaning that it is possible to have two or more of the same Elements in a Tuple.
Remember, that when choosing a the Python Iterables (List, Tuple, Set or Dictionary) for your code, it is very important to choose the correct one for the required use case, as each of the Python Iterables has it own qualities and properties, which have a direct influence on both performance and security of your code.
Full Python Beginners Course
This tutorial is just a small sample of the my Full Python Beginners Course. The entire course is recorded and available in High Definition video, allowing you to easily learn Python as you watch and follow along. If you have been wanting to start learning Python, but haven’t been sure where to start, then this is the course for you, so don’t to miss out!
Share the love
If you enjoyed this tutorial content and would like others to benefit from it as well, make sure to share it on your favorite Social Media platform, using the share buttons below.
Subscribe for News & Discount Offers
Subscribe right now to gain instant access to the latest news and tutorials while also being the first to know about, exclusive offers and discounts!