Last updated on August 8, 2022
There are four collection data types in the Python programming language and Tuple is one of them, the other 3 are List, Set, and Dictionary, and each has different usage.
A tuple is a collection that is ordered and unchangeable and it allows duplicate members. You can remove and/or add items to a Tuple. And Tuple can hold different data types.
Tuple items are indexed, the first item has index [0]
, the second item has index [1]
etc.
Creating a Tuple
A tuple is created by placing the elements inside parentheses, separated by commas. The parentheses are optional, however, it is a good practice to use them.
If you’re generating a tuple with a single element, make sure to add a comma after the element.
Tuple Examples:
# Different types of tuples
# Empty tuple
my_tuple = ()
print(my_tuple)
# Tuple without parentheses
my_tuple = 1, 2, 3
print(my_tuple)
# Tuple with single element
# Tuple without parentheses
my_tuple = (1,)
print(my_tuple)
# Tuple having integers
my_tuple = (1, 2, 3)
print(my_tuple)
# tuple with mixed datatypes
my_tuple = (1, "Hello World", 4.4)
print(my_tuple)
# tuple unpacking
a, b, c = my_tuple
print(a) # Output: 1
print(b) # Output: Hello World
print(c) # Output: 4.4
# nested tuple
my_tuple = ("arjunphp", [1, 2, 3], (4, 5, 6))
print(my_tuple)
# Code to create a tuple with repetition
my_tuple = ('arjunphp',)*3
print(my_tuple)
# output: ('arjunphp', 'arjunphp', 'arjunphp')
# Try the above without a comma and check. You will get my_tuple as a string ‘arjunphparjunphparjunphp’.
Basic Tuples Operations
Tuples respond to the + and * operators much like strings; they mean concatenation and repetition here too, except that the result is a new tuple, not a string.
Python Expression | Results | Description |
---|---|---|
len((1, 2, 3)) | 3 | Length |
(1, 2, 3) + (4, 5, 6) | (1, 2, 3, 4, 5, 6) | Concatenation |
(‘Hi!’,) * 4 | (‘Hi!’, ‘Hi!’, ‘Hi!’, ‘Hi!’) | Repetition |
3 in (1, 2, 3) | True | Membership |
for x in (1, 2, 3): print x, | 1 2 3 | Iteration |
Built-in Tuple Functions
Below are the Tuple functions:
len(tuple) – Gives the total length of the tuple.
tuple(seq) – Converts a list into tuple.
cmp(tuple1, tuple2) – Compares elements of both tuples.
max(tuple) – Returns item from the tuple with max value.
min(tuple) – Returns item from the tuple with min value.
Comments are closed, but trackbacks and pingbacks are open.