Python Tuple tuple() Method
The Python Tuple tuple() method is used to convert a list of items into tuples.
A tuple is a collection of python objects that are separated by commas which are ordered and immutable. Tuples are sequences, just like lists. The difference between tuples and lists are: tuples cannot be changed unlike lists and tuples use parentheses, whereas lists use square brackets.
Syntax
Following is the syntax of Python Tuple tuple() method −
tuple(seq)
Parameters
seq − This is a sequence to be converted into tuple.
Return Value
This method returns this tuple.
Example
The following example shows the usage of Python Tuple tuple() method. Here a list 'aList' is creating which consists of strings as its elements. Then this list is converted into tuple using tuple() method.
aList = ['xyz', 'zara', 'abc']
aTuple = tuple(aList)
print ("Tuple elements : ", aTuple)
When we run above program, it produces following result −
Tuple elements : ('xyz', 'zara', 'abc')
Example
In here, we are creating a dictionary 'dict1'. Then this dictionary is passed as an argument to the tuple() method. Thereafter, we retrieve the tuple of the dictionary.
# iterable dictionary
dict1 = {'Name': 'Rahul', 'Hobby': 'Singing', 'RollNo': 45}
# using tuple() method
res = tuple(dict1)
# printing the result
print("dictionary to tuple:", res)
While executing the above code we get the following output −
dictionary to tuple: ('Name', 'Hobby', 'RollNo')
Example
Now, we will create a string. Then this string is passed as an argument to the tuple() method. Thereafter, we retrieve the tuple of the string.
# iterable string
string = "Tutorials Point";
# using tuple() method
res = tuple(string)
# printing the result
print("converted string to tuple:", res)
Following is an output of the above code −
converted string to tuple: ('T', 'u', 't', 'o', 'r', 'i', 'a', 'l', 's', ' ', 'P', 'o', 'i', 'n', 't')
Example
The tuple() method does not raise any error if an empty tuple is passed in this method. It returns an empty tuple.
# empty tuple
tup = tuple()
print("Output:", tup)
Output of the above code is as follows −
empty tuple: ()
Example
The tuple() method raises a TypeError, if an iterable is not passed. The code given below explains it.
#a non-iterable is passed as an argument
tup = tuple(87)
# printing the result
print('Output:', tup)
We get the output of the above code as shown below −
Traceback (most recent call last):
File "C:\Users\Lenovo\Desktop\untitled.py", line 2, in <module>
tup = tuple(87)
TypeError: 'int' object is not iterable