Python Tuples
Python tuple created inside the rounded bracket and it unchangeable ordered.
How to declare python tuple?
>>> tup = (“Welcome”, “to”, “the”, “Codersarts”)
Accessing Tuple item
The item of tuple is accessed using the index value.
It works as per above list accessing process like that –
>>> tup[2]
Output:
the
Extract element using the negative indexing
It works like a list in python, the negative index starts from last.
>>> tup[-1]
Output:
Codersarts
Tuple with range
Like list, the tuple is also extracted the element from string using the given range
>>> string = ("hi", "this", "is", "codersarts", "tutorial")
>>> string[2:4]
Output:
is codersarts tutorials
Negative indexing is also used like list.
How to change tuple value
Once a tuple is created it is not changed, it can be changed using the list.
a = ("Hi", "this", "is", "codersarts")
b = list(x)
b[1] = "hello"
a = tuple(b)
print(x)
Output:
hello this is codersarts
Passing tuple with the loop
The tuple is passed from loop like list.
a = ("Hi", "this", "is", "codersarts")
for x in a:
print(x)
Output:
Hi
this
is
codersarts
Finding the length of tuple
a = ("Hi", "this", "is", "codersarts")
print(len(x))
Output:
4
Add item to tuple
Once a tuple is created not add another item to the tuple.
Removing item from tuple
We can't remove the item from tuple after it is created.