What Are Python Tuples? How to Create Tuple in Python?
What are Tuples in Python?
Tuples store an ordered list of items, and are unchangeable. This signifies that the values of a tuple can’t be changed. Parentheses are used to define tuples.
In Python, a tuple is a basic data structure. They let you keep a list of objects in a specific order. A tuple can be used to hold a list of employee names, for example. You can also use it to hold a list of ice cream flavors available at an ice cream parlor.
How to Create Python Tuple?
A Tuple is a group of Python objects separated by commas. A tuple is the same as a list in terms of indexing, nested items, and repetition, but it is immutable, whereas lists are mutable.
# An empty tuple empty_tuple = () print (empty_tuple)
# Creating non-empty tuples # One way of creation tup = 'python', 'WSC' print(tup) # Another for doing the same tup = ('python', 'WSC') print(tup)
Note: In case you're generating a tuple with a single element, make sure to add a comma after the element.
How to Access Data From Tuple?
Each item in a tuple has its own index value, which begins at zero. The index values are incremented by one. The index value of an individual item in a tuple can be used to access it.
Here are the index values for the tuple declared above:
We can now access a single element separately because we know the index values for each item. We can fetch the item with the index value 3 by using the following code:
A negative index value is assigned to each item in a tuple. These variables allow us to count backward from a tuple's end. They begin with a negative value. If you're working with a big list, a negative index number may be handier. This is because you may work your way backward from the end of the list.
The negative index values for our ice cream flavors tuple are as follows:
The following code can be used to retrieve the value at the index point of -1:
The following is the output of our code: Choc-Chip.
How to Update or Delete Data from Tuple?
You can't change tuples in Python since they're immutable sequences. In tuples, you can't add, edit, or remove things (elements).
Tuples indicate data that does not need to be updated. Thus if you need to change it, you should use a list instead of a tuple. If you need to edit a tuple anyhow, you can convert it to a list, update it, and then make it a tuple.
Take the following tuple as an example.
t1 = (0, 1, 2)
# (0, 1, 2)
# <class 'tuple'>
It also helps you to get elements like lists using index  or slice [:].
# (0, 1)
Since the tuples can't be immuted, a new value to the element can't be assigned.
# t1 = 100
# TypeError: 'tuple' object does not support item assignment
Destructive methods (= methods that update the original object) such as append() in the list are not defined in the tuple.
# AttributeError: 'tuple' object has no attribute 'append'