tuple Data TypeThe predefined data type tuple is a collection data type.
A is an ordered collection of elements.tuple
The elements of a have a position index starting with the value tuple0.
A variable consists of elements separated by commas and delimited by parenthesis tuple( ).
Example
data = (2, 3, 5, 7)
The elements of a can be of different types.tuple
A Python is bounded and iterable: you can iterate over these elements in a tuplefor loop.
A variable is immutable in nature: unlike a tuplelist variable, a variable cannot be modified.tuple
A variable can be considered a read-only tuplelist variable.
Nested tuple
A can have one element of type tuple.tuple
Access
You access the elements of a using the tuple[ ] and [:] operators.
Operations
The concatenation operator is the symbol +
The repetition operator is the symbol *
The membership operator is in
The non-membership operator is not in
Expression
Result
Description
(1, 2, 3) + (4, 5, 6)
(1, 2, 3, 4, 5, 6)
Concatenate
('A') * 3
('A', 'A', 'A')
Repetition
3 in (1, 2, 3)
True
Membership
Example
some_primes = (2, 3, 5, 7)
print (some_primes)
print (some_primes[0])
more_primes = (11, 13, 17, 19)
primes = some_primes + more_primes
print (primes)
print (primes[2:6])
print (primes[2:])
The length of a tuple is the number of elements that make up the .tuple
The len() function gives the length of a .tuple
Example
colors = ('Red', 'Green', 'Blue')
print('Total elements:', len(colors))
A is limited and iterable: we can iterate through its elements in a tuplefor loop.
We use the membership operator in to iterate through the elements of a .tuple
Example
fruits = ('apple', 'banana', 'orange')
# iterate through the tuple
for fruit in fruits:
print(fruit)
Below are the built-in methods for tuples.
Method
Description
tuple.count(obj)
Returns count of how many times obj occurs in tuple.
tuple.index(obj)
Returns the lowest index at which obj appears in tuple.