Tuples are ordered sequences of values with immutable properties. Immutable lists can also be described as read-only lists.
Tuples Properties
- Tuples are ordered sequences.
- Adding or removing values or changing the order is impossible since it is immutable.
- A tuple can have duplicate values, just like a list.
- The length of tuples is fixed due to immutability.
Python Tuple Comprehension
You can’t create tuple comprehension-like lists in Python, but using a small workaround you can create python tuple comprehension. list1 = [i for i in 10]. The following is an example of list compression. You can try this same method with Parentheses, but it won’t create a tuple. It creates a generator object instead of tuples.
tup1 = (i for i in range(10))
print(tup1)
Output
<generator object <genexpr> at 0x000001F37AA5EEB0>
So to make tuple comprehension, you need to use like
tup1 =tuple(i for i in range(10)) # Python Tuple Comprehension
print(type(tup1), tup1)
Python Tuples Methods
Python tuple methods are count and index, as seen below.
Tuple count Method
To count an element in a tuple, use a tuple count. This function returns the number of times the element appears.
tup1=(1,2,3,4,4)
print(tup1.count(4))
Tuple Index Method
This method returns the first index or position of a value passed to it. A value error will be thrown if the value is not present.
a.index(x, start, end)
x: any value that needs to be checked in the tuple.
Start (integer) start position of the value to be searched
End (integer) end position upto this position checks the value.
Tuple Value Error Sample.
tup1=(1,2,3,4,4)
tup1.index(55)
ValueError: tuple.index(x): x not in tuple
a.index(4)
The above code returns 3. 4 available in two positions, i.e., 3, 4, but the index returns first.
Python Tuple of Tuples
You can have tuples inside a tuple in python.
cord=(("IND",(1,2)), ("USA",(4,5)))
print(type(cord))
print(type(cord[0]))
print(type(cord[0][0])) # String
print(type(cord[0][1]))
Here is a sample Python code for a tuple of tuples. Using this code, you can see cord is a tuple, and cord 0th index is a tuple as well. The zeroth index also has two indexes, the first one being a string and the second a tuple.
Python Unpack Tuple into Variables
Tuples can be unpacked completely or partially into variables. In order to unpack the tuple completely, you need to provide a variable equal to the length of the tuple. If you want to partially unpack, you can use the * symbol.
# Complete Unpack
log11=(11,10,2021)
day, mon, year=log11
print(day, mon, year)
11 10 2021
Partial Unpack
tup1=(1,2,3,4,4)
x,*y=tup1
print(x)
print(y)
1
[2, 3, 4, 4]
Empty Tuple Python
By using parentheses, you can create a tuple. However, you cannot create a tuple with just one element and parentheses.
a= (1)
print(a)
You might think it is a tuple but let’s run the program and see. It’s an integer, not a tuple. In other words, a tuple has only one element when there is a comma in it.
<class 'int'>
Another Example
tuple1=(1,)
tuple2=(2)
print(type(tuple1), type(tuple2))
<class 'tuple'> <class 'int'>
To create an empty tuple, you need to use the tuple keyword or just with parentheses (,).
empty_tuple1 = ()
empty_tuple2 = tuple()
print(type(empty_tuple1), type(empty_tuple2))
Tuple concatenation python and Combine Tuples
Python tuples are immutable, so we cannot add or remove items within a tuple, but we concatenate using the + operator and store in a different object.
Tuples are immutable, so the only methods you can see are count and index for them.
tup1=(1,2,3,4)
tup2=(3,4,5)
print(id(tup1))
# Method 1
tup3 = tup1 + tup2
print(id(tup1))
# Method 2
tup1 = tup1 + tup2
print(id(tup1))
print(tup1)
2625576084880
2625576084880
2625576222976
(1, 2, 3, 4, 3, 4, 5)
Explanation
The first thing we did was to create two tuples, one named tup1 and the other named tup2. Find out what the tup1 object’s id is. Now concatenate both tuples and store in tup3. Verify again the id of tup1.
Finally, concatenate both tuples and store them in tup1 and verify the tuple’s id. Here you can see there is another object id for the tup1 object.
In method 1, we are concatenated and stored in a different variable and method 2, and we use the same variable to store.
Python Convert Tuple to String
There are times when we need to convert a tuple to a string. There are a number of ways to do that, and we will examine a few of them below.
1) Convert a tuple to a string using the join method.
2) Make use of for loops
3) Use the reduce method
tup1=('a','b','d','f','e')
tup1="".join(tup1)
print(type(tup1))
For loops combine tuples to strings, but in this case if there is an integer it will throw an error.
tup1=('a','b','d','f','e')
str1=""
for item in tup1:
str1+=item
print(str1)
abdfe
In order to convert a tuple to a string that has an integer, you must convert all items in a tuple to strings first..
Python tuple Object
Python is immutable; can we use a list inside a tuple? Is it possible to change the list? The following program shows you how. As well as tuple, even, int, string, and range are immutable.
First, let’s create a tuple with the list, int, string and dict.
In the next step, we will print and update the list value in that tuple and then print again. Additionally, I updated the dictionary also.
tup1=(1,2,3,[4,5],{"a":5,},"gopi")
print(tup1)
tup1[3][1]=6 # Updating a list inside the tuple
print(tup1)
tup1[4]["b"]=10 # Updating a dict inside the tuple
print(tup1)
(1, 2, 3, [4, 5], {'a': 5}, 'gopi')
(1, 2, 3, [4, 6], {'a': 5}, 'gopi')
(1, 2, 3, [4, 6], {'a': 5, 'b': 10}, 'gopi')
Under Python Tuple, these topics are important. Hopefully this article covers most of the Python tuple topics, but if anything is missed, please let us know.