What is tuple?
In Python programming, a tuple is similar to a list. The difference between the two is that we cannot change the elements of a tuple once it is assigned whereas in a list, elements can be changed.
A tuple is a collection which is ordered and unchangeable. In Python tuples are written with round brackets.
Advantages of Tuple over List
Since, tuples are quite similar to lists, both of them are used in similar situations as well.
However, there are certain advantages of implementing a tuple over a list.
Below listed are some of the main advantages:
• We generally use tuple for heterogeneous (different) data types and list for homogeneous (similar) datatypes.
• Since tuple are immutable, iterating through tuple is faster than with list. So there is a slight performance boost.
• Tuples that contain immutable elements can be used as key for a dictionary. With list, this is not possible.
• If you have data that doesn’t change, implementing it as tuple will guarantee that it remains write-protected.
Creating a Tuple
A tuple is created by placing all the items (elements) inside a parentheses (), separated by comma. The parentheses are optional but is a good practice to write it.
A tuple can have any number of items and they may be of different types (integer, float, list, string etc.).
# empty tuple
n = ()
# tuple having integers
n = (1, 2, 3)
# tuple with mixed datatypes
n = (1, “Hello”, 3.4)
# nested tuple
n = (“mouse”, [8, 4, 6], (1, 2, 3))
Creating a tuple with one element is a bit tricky.
# only parentheses is not enough
n = (“hello”)
print(type(n))
# Output: <class ‘str’>
# need a comma at the end
n = (“hello”,)
print(type(n))
# Output: <class ‘tuple’>
# parentheses is optional
n = “hello”,
print(type(n))
# Output: <class ‘tuple’>
Creating tuples from existing sequences
We can use the built-in type object (tuple()) to create tuple from sequences using the syntax given below.
t=tuple(<sequence>)
where <sequence> can be any kind of sequence object including string , list and tuples.
Python creates the individual elements of the tuple from the individual elements of passed sequence. If we pass in another tuple , the tuple function make a copy.
Example:
t1=tuple(‘computer’)
print(t)
Output:
(‘c’, ‘o’, ‘m’, ‘p’, ‘u’, ‘t’, ‘e’, ‘r’)
>>>
Example:
t2=tuple(‘hello’)
print(t2)
Output:
(‘h’, ‘e’, ‘l’, ‘l’, ‘o’)
>>>
We can also create a tuple by taking input from the user.
Example:
n=input(“Enter tuple elements “)
t1=tuple(n)
print(t1)
Output:
Enter tuple elements Computer
(‘C’, ‘o’, ‘m’, ‘p’, ‘u’, ‘t’, ‘e’, ‘r’)
>>>
The most commonly use method to input a tuple is eval(input()) as given below:
Example:
n=eval(input(“Enter tuple elements “))
print(n)
t1=tuple(n)
print(t1)
Output:
Enter tuple elements (1,2,3,’hello’,10)
(1, 2, 3, ‘hello’, 10)
(1, 2, 3, ‘hello’, 10)
>>>