What is tuple in Python?
Tuple is one of 4 built-in data types in Python. The other 3 are Dictionary, Set, and List, all of which can be used to store a collection of elements/items,
The following lists a few key characteristics of Tuple.
- The elements in a Tuple are ordered.
- The elements in a Tuple are unchangeable. In the language of Python, we refer to a value that cannot change as immutable. In other words, a tuple is an immutable list.
- You can create a Tuple by using round brackets.
How to define a Tuple
A tuple can be defined by using parentheses ()
. This is different from a list, which uses square brackets []. The following code example shows how you can define a Tuple.
cars = ("Tesla", "Ford", "Toyota")
print(cars)
print(type(cars))
('Tesla', 'Ford', 'Toyota') <class 'tuple'>
Loop through a Tuple
You can also use a loop to print them separately. The following code example shows how you can print the elements in a Tuple one by one (i.e., Looping).
cars = ("Tesla", "Ford", "Toyota")
for car in cars:
print(car)
Tesla Ford Toyota
You can also use a combination of range()
and len()
to loop through a Tuple.
cars = ('Tesla', 'Ford', 'Toyota')
for i in range(len(cars)):
print(cars[i])
Tesla Ford Toyota
Element Type within a Tuple
The elements in a Tuple can be the same type or different types. For instance, it can include all numbers, strings, or booleans. It can be a combination of them. The following are examples.
Tuple_1 = (3, 9, 8)
Tuple_2 = ('Tesla', 'Ford', 'Toyota')
Tuple_3=(3,'Tesla',True)
print(Tuple_1,Tuple_2,Tuple_3)
(3, 9, 8) ('Tesla', 'Ford', 'Toyota') (3, 'Tesla', True)
Type() with Tuple
The following example shows how you can check whether it is a Tuple.
Tuple_3=(3,'Tesla',True)
print(type(Tuple_3))
<class 'tuple'>
tuple() Constructor
You can also use the tuple() to define a Tuple. Note that, you need to use double round brackets. The following is an example of how to use tuple() to define a Tuple in Python.
Tuple_Example = tuple(('Tesla', 'Ford', 'Toyota'))
print(Tuple_Example)
The following is the output after running the code above. It shows the defined Tuple example.
('Tesla', 'Ford', 'Toyota')
Combine Multiple Tuples
You can use the plus (+) to combine multiple Tuples. The following is an example. Note that, this example illustrates that Tuples allow repeated elements.
Tuple_1 = (3, 9, 8)
Tuple_2 = ('Tesla', 'Ford', 'Toyota')
Tuple_3=(3,'Tesla',True)
Tuple_combined=Tuple_1+Tuple_2+Tuple_3
print(Tuple_combined)
The following is the output, showing the combined Tuple.
(3, 9, 8, 'Tesla', 'Ford', 'Toyota', 3, 'Tesla', True)