Python Tuples
Tuples
Tuples can be used for the storage in one variable of multiple items.
A tuple is one of 4 built-in data types in Python that is used for the storage of data collections the other 3 are List, Set, and Dictionary, all having various properties and uses.
A tuple is an arranged and unchangeable collection.
Note :- Round brackets ()
are used to create tuples.
Example :- Create a simple tuple
mytuple = ("red", "green", "blue")
print(mytuple)
Output :-
Tuple Items
Multiple items are ordered, unmodified, and allow for duplicate values.
Multiple items are indexed, with the first item having index [0]
, the second item having index [1]
and so on.
Ordered
When we state that tuples are sorted, we're referring to the fact that the items are in a specific sequence that will not change.
Unchangeable
Tuples are immutable, which means that once they've been created, they can't be changed, added to, or removed.
Allow Duplicates
Tuples can have items with the same value because they're indexed :
Example :- A tuple with duplicate values :
mytuple = ("red", "green", "blue", "red", "blue")
print(mytuple)
Output :-
Tuple Length
Use the len()
function to find out how many items are in a tuple :
Example :- The number of items in the tuple should be printed :
mytuple = tuple(("red", "green", "blue"))
print(len(mytuple))
Output :-
Related Links
Check if Item Exists
The in
keyword can be used to determine if a particular item is contained in a tuple.
Example :- Check to see if "green" appears in the tuple :
mytuple = ("red", "green", "blue")
if "green" in mytuple:
print("Yes, 'green' is in the mytuple")
Output :-
Create Tuple With One Item
You must add a comma to create a tuple with only a single item, otherwise, Python will not recognize that as a tuple.
Example :- One item tuple, remember the comma :
mytuple = ("red",)
print(type(mytuple))
# NOT a tuple
mytuple = ("red")
print(type(mytuple))
Output :-
<class 'str'>
Tuple Items - Data Types
Any data type can be used in a tuple item :
Example 1 :- Creating multiple tuples with different datatypes like string, int and boolean.
tuple1 = ("red", "green", "blue")
tuple2 = (1, 5, 7, 9, 3)
tuple3 = (True, False)
print(tuple1)
print(tuple2)
print(tuple3)
Output :-
(1, 5, 7, 9, 3)
(True, False)
A tuple can have different data typesof data in it.
Example 2 :- Strings, numbers, and boolean values are all included in this tuple :
tuple1 = (111, "abc", 5.5, True)
print(tuple1)
Output :-
type()
Python defines tuples as objects with the 'tuple' type of data.
Example :- What is the data type of a tuple?
mytuple = ("red", "green", "blue")
print(type(mytuple))
Output :-
The tuple() Constructor
The tuple()
constructor can also be used to generate a tuple.
Example :- Using the tuple()
method to make a tuple :
mytuple = tuple(("red", "green", "blue"))
print(mytuple)
Output :-
Related Links
Access Tuple Items
Index numbers in square brackets can be used to access tuple items.
Example :- The third item in the tuple should be printed :
mytuple = ("red", "green", "blue")
print(mytuple[2])
Output :-
Note: The first item has an index of 0
.
Negative Indexing
Indexing in the negative direction involves starting at the end of a list.
-1
refers to the last item, -2
refers to the second last item etc.
Example :- The tuple's last item should be printed :
mytuple = ("red", "green", "blue")
print(mytuple[-1])
Output :-
Range of Indexes
You can provide a range of indexes by defining where to begin and where to end the range.
Any range supplied will produce a tuple with the specified elements in it as its return value.
Example 1 :- The third, fourth, and fifth items should be returned :
mytuple = ("red", "green", "blue", "orange", "gray", "white", "black")
print(mytuple[2:5])
# This will return the items from position 2 to 5.
# Remember that the first item is position 0,
# and note that the item in position 5 is NOT included
Output :-
Note: Index 2 (included) is the starting point for the search. Index 5 is the ending point (not included).
Remember that the first item has an index of 0.
It is not necessary to specify a start value for the range to begin at the first item :
Example 2 :- "gray" is NOT included in this example, which returns all things from the beginning to the end range :
mytuple = ("red", "green", "blue", "orange", "gray", "white", "black")
print(mytuple[:4])
Output :-
The range will extend to the end of the list if the end value is not specified :
Example 3 :- As you can see, this example returns the elements from "orange" to the end of the tuple :
mytuple = ("red", "green", "blue", "orange", "gray", "white", "black")
print(mytuple[3:])
Output :-
Python - Update Tuples
It is impossible to add or remove items from a tuple once it has been created because tuples are unchangeable once they are created.
However, there are several workarounds that can be used.
Change Tuple Values
When creating a tuple, its values can't be changed. They are immutable, as they are sometimes termed.
There is, however, a way to get around this issue. Just follow the below steps to change a tuple values :
- Create a tuple.
- Convert tuple as list using
list()
method. - Change the value in the list.
- Convert the list as new tuple using
tuple()
method.
Exmaple :- Changing a tuple value :
x = ("red", "green", "blue")
y = list(x)
y[1] = "orange"
x = tuple(y)
print(x)
Output :-
Add Items
There is no built-in append()
method for tuples because they are immutable, but there are various ways to put things into tuple.
1. To work around this, you can change the tuple into a list, add your item(s), and then convert it back into a tuple.
Example 1 :- Converting the tuple to a list, then add "orange" before returning it to a tuple :
mytuple = ("red", "green", "blue")
y = list(mytuple)
y.append("orange")
mytuple = tuple(y)
print(mytuple)
Output :-
2. Tuples can be added together by adding one to another. As tuples can be added to tuples, creating a new tuple containing the item(s) and adding it to the existing tuple is an option.
Example 2 :- Add items from another tuple :
x = ("red", "green", "blue")
y = ("white", "black")
x += y
print(x)
Output :-
Note :- A comma must be used after the item when producing a tuple with only one item, or else the tuple won't be recognised as such.
Remove Items
Note: Items in a tuple can't be removed.
You can't remove things from a tuple because it's unchangeable, but you can use the same workaround we used for modifying and adding tuple elements in the above program.
Example 1 :- Convert the tuple to a list, remove "red", and convert it back to a tuple :
mytuple = ("red", "green", "blue")
y = list(mytuple)
y.remove("red")
mytuple = tuple(y)
print(mytuple)
Output :-
or You can also delete the entire tuple.
Example 2 :- It is possible to delete the tuple completely by using the del
keyword :
mytuple = ("red", "green", "blue")
del mytuple
print(mytuple) #this will raise an error because the tuple no longer exists
Output :-
File "demo_tuple_del.py", line 3, in < module>
print(mytuple) #this will raise an error because the tuple no longer exists
NameError: name 'mytuple' is not defined
Unpacking a Tuple
It's common for us to assign values to a tuple after we generate it. A tuple is "packed" in this way.
Extracting values from a tuple is called unpacking.
Example :- Packing a tuple :
colors = ("red", "green", "blue")
print(colors)
Output :-
Python allows us to extract the values back into variables, though. "Unpacking" is the term for this process :
Example 2 :- Unpacking a tuple :
colors = ("red", "green", "blue")
(r, g, b) = colors
print(r)
print(g)
print(b)
Output :-
green
blue
Note :- When there are more variables than values in a tuple, you'll need to use a "asterisk" to aggregate the remaining values into one list.
Using Asterisk*
Variable names can be prefixed with a *
to indicate that a list of values will be assigned to them if there are fewer variables than values.
Example 1 :- Create a asterisk variable called "b" for the rest of the data :
colors = ("red", "green", "blue", "white", "black")
(r, g, *b) = colors
print(r)
print(g)
print(b)
Output :-
green
['blue', 'white', 'black']
Python will assign values to a variable until the number of values left equals the number of variables remaining if an asterisk is added to a variable name other than the final.
Example 2 :- Please add the "g" variable a value list :
colors = ("red", "green", "blue", "white", "black")
(r, *g, b) = colors
print(r)
print(g)
print(b)
Output :-
['green', 'blue', 'white']
black
Python - Loop Through a Tuples
It is also possible to loop through the tuple items using a for
-loop.
Example :- Iterate through the elements and print out the tuple values.
mytuple = ("red", "green", "blue")
for x in mytuple:
print(x)
Output :-
green
blue
Loop Through the Index Numbers
It's also possible to loop through the tuple items by referring to their index number.
You may generate a suitable iterable by using the range()
and len()
functions to create a list.
Example :- All items can be printed by referring to their corresponding index number :
mytuple = ("red", "green", "blue")
for i in range(len(mytuple)):
print(mytuple[i])
Output :-
green
blue
Using a While Loop
Using a while loop, you may iterate through the list elements.
To get the length of the tuple, use the len()
function, then begin at 0 and loop through the tuple members using their indexes.
Remember to increment the index by one after each iteration.
Example :- Using a while
loop to iterate through all of the index numbers, print all items :
mytuple = ("red", "green", "blue")
i = 0
while i < len(mytuple):
print(mytuple[i])
i = i + 1
Output :-
green
blue
Python - Join Tuples
The +
operator can be used to merge two or more tuples :
Join Two Tuples
You can use the +
operator to join two tuples into one.
Example :- Join two tuples
tuple1 = ("a", "b" , "c")
tuple2 = (1, 2, 3)
tuple3 = tuple1 + tuple2
print(tuple3)
Output :-
Multiply Tuples
The *
operator can be used to multiply the contents of a tuple by a specified number of times.
Exmaple :- In this case, the colors tuple is multiplied by 2 :
colors = ("red", "green", "blue")
colors2 = colors * 2
print(colors2)
Output :-