Creating a Tuple
If you are a beginner in Python programming, you might have come across the term tuple. In simple terms, a tuple is an ordered collection of elements. Unlike Python lists, tuples are immutable, which means that they cannot be modified once created.
In this article, you will learn how to create tuples using different approaches in Python programming.
Creating a Tuple
Here are some ways to create tuples in Python:
Method 1: Using parenthesis
One of the easiest and most common ways of creating a tuple is by using parenthesis. In the tuple, the elements are separated by commas.
# Creating a tuple with integers my_tuple = (1, 2, 3, 4, 5) # Creating a tuple with strings fruits_tuple = ('apple', 'banana', 'orange')
In the above code, we created two tuples, one with integers and the other with strings. Notice that we defined the tuples using parenthesis and separated the elements with commas.
Method 2: Using the tuple() constructor
Another way to create a tuple is by using the tuple() constructor.
# Creating a tuple with integers my_tuple = tuple((1, 2, 3, 4, 5)) # Creating a tuple with strings fruits_tuple = tuple(('apple', 'banana', 'orange'))
In the above code, we used the tuple() constructor to create the tuples. We passed the elements as an argument to the tuple() constructor, then stored the result in a variable.
Method 3: Creating a tuple with a single element
What happens when you try to create a tuple with a single element, and you define it using parenthesis?
my_tuple = (1) # Will it create a tuple? print(type(my_tuple)) # No, it's not a tuple. It's an integer.
The above code will not create a tuple but instead it will create an integer. To create a tuple with a single element, use a comma after the element.
my_tuple = (1,) print(type(my_tuple)) # Yes, it's a tuple.
In the above code, we defined a tuple with a single element.
Conclusion
Congratulations! You have learned how to create tuples in Python. We went through three different methods for creating tuples. Remember that tuples are immutable, so once created, you cannot modify them.