CBSE Class 11 : Python | Tuples 2

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)
>>>