In Python, a tuple is an immutable sequence, meaning that once it’s created, you can’t modify it (no adding, removing, or changing elements). Tuples often store multiple items in a single variable, especially when the data should remain constant throughout the program. Here’s a breakdown of key points about tuples:
The tuple object (pronounced “toople” or “tuhple,” depending on who you ask) is roughly like a list that cannot be changed—tuples are sequences, like lists, but they are immutable, like strings
Creating a Tuple with Multiple Elements
Tuples are created by placing values inside parentheses () separated by commas:
tupleData = (1, 2, 3, 4, 5)
Creating a Tuple Without Parentheses (Tuple Packing)
You can also create a tuple by simply listing values separated by commas without parentheses (this is called tuple packing):
tupleData = 1, 2, 3, 4, 5
Creating an Empty Tuple
An empty tuple can be created by using empty parentheses:
empty_tuple = ()
Creating a Tuple with a Single Element
To create a tuple with a single item, you need to add a comma after the element. Without the comma, Python treats it as a single value in parentheses:
single_item_tuple = (6,) # This is a tuple with one element
not_a_tuple = (6) # This is just an integer, not a tuple
Using the tuple() Constructor
You can create a tuple from other iterable types (like lists or strings) by using the tuple() constructor:
# From a list
my_list = [1, 2, 3, 4, 5]
tuple_from_list = tuple(my_list)
# From a string
string = "hello"
tuple_from_string = tuple(string)
Python Tuple – Questions and Answers
Q 1: What is a tuple in Python?
Ans: A tuple is an ordered, immutable collection of items.
Q 2: How do you create a tuple?
Ans: Using parentheses, e.g., my_tuple = (1, 2, 3).
Q 3: Can a tuple contain duplicates?
Ans: Yes, tuples can have repeated values.
Q 4: Are tuples mutable?
Ans: No, tuples cannot be changed after creation.
Q 5: Can a tuple store different data types?
Ans: Yes, tuples can contain mixed data types.
Python Tuple – Objective Questions (MCQs)
Q1. Which of the following correctly creates a tuple in Python?
Q2. What is the main difference between a list and a tuple in Python?
Q3. What will be the output of the following code?
t = (10, 20, 30)
print(t[1])
Q4. How can you create a tuple with a single element?
Q5. What will happen if you try to change a tuple element?
t = (1, 2, 3)
t[0] = 5