In this section, we'll explore the concept of tuples in Python.
Tuples are ordered, immutable sequences that can store various types of data. We'll learn how to create, access, and manipulate tuples effectively.
We'll learn about the following topics:
Name | Type in Python | Description | Example |
---|---|---|---|
Tuples | tuple | Comma-separated ordered immutable sequence of objects in parentheses ( ). | (10,'hello', 15.9) |
type((23, 98.3, 'hello'))
tuple
Tuples in Python are created using parentheses ()
. You can include elements within the parentheses, separated by commas.
a = ('one', 23, 98.3, 'hello')
If you try to define a tuple with one item.
type((2))
int
To tell Python that you really want to define a singleton tuple, include a trailing comma (,) just before the closing parenthesis.
type((2,))
tuple
This is another way to define a tuple's items.
x1, x2, x3 = 4, 5, 6
t = x1, x2, x3
print(t)
type(t)
(4, 5, 6)
tuple
len()
:Python's built-in len() function determines the total number of elements within a tuple's sequence.a = ('one', 23, 98.3, 'hello')
len(a)
4
print(a)
('one', 23, 98.3, 'hello')
Elements in a tuple can be accessed individually by using square brackets and an index, just like accessing individual characters in a string. All lists, tuples, and strings indexing follow a zero-based approach.
#Grab element at index 0
a[0]
'one'
#Grab index 1 and everything past it
a[1:]
(23, 98.3, 'hello')
#Grab everything UP TO index 2
a[:2]
('one', 23)
a[2:len(a)]
(98.3, 'hello')
Negative indexing allows counting from the end of the tuple.
a[-1]
'hello'
a[:-3]
('one',)
[start:stop:step]
a[::2]
('one', 98.3)
You can specify a negative step value as well, in which case Python steps backward through the tuple. In that case, the starting/first index should be greater than the ending/second index.
a
('one', 23, 98.3, 'hello')
a[4:0:-2]
('hello', 23)
This is a common paradigm for reversing a tuple.
a[::-1]
('hello', 98.3, 23, 'one')
a = ('one', 23, 98.3, 'hello')
b = (23, 98.3, 'one', 'hello')
a is b
False
a == b
False
This is the biggest difference between Tuples and Lists.
a
('one', 23, 98.3, 'hello')
a[0] = 2
--------------------------------------------------------------------------- TypeError Traceback (most recent call last) ~\AppData\Local\Temp\ipykernel_18304\4221126460.py in <module> ----> 1 a[0] = 2 TypeError: 'tuple' object does not support item assignment
a.append('new')
--------------------------------------------------------------------------- AttributeError Traceback (most recent call last) ~\AppData\Local\Temp\ipykernel_18304\2298863157.py in <module> ----> 1 a.append('new') AttributeError: 'tuple' object has no attribute 'append'
a = a + ('new')
--------------------------------------------------------------------------- TypeError Traceback (most recent call last) ~\AppData\Local\Temp\ipykernel_18304\1405506363.py in <module> ----> 1 a = a + ('new') TypeError: can only concatenate tuple (not "str") to tuple
a.remove('one')
--------------------------------------------------------------------------- AttributeError Traceback (most recent call last) ~\AppData\Local\Temp\ipykernel_18304\3225995218.py in <module> ----> 1 a.remove('one') AttributeError: 'tuple' object has no attribute 'remove'
Nothing can be added/removed/replaced in tuples unlike lists.
del a[0]
--------------------------------------------------------------------------- TypeError Traceback (most recent call last) ~\AppData\Local\Temp\ipykernel_18304\3074760810.py in <module> ----> 1 del a[0] TypeError: 'tuple' object doesn't support item deletion
a * 2
('one', 23, 98.3, 'hello', 'one', 23, 98.3, 'hello')
in
: Python also provides a membership operator that can be used with tuples. The in operator returns True if the first operand is contained within the second, and False otherwise.'one' in a
True
not in
: Python also provides a membership operator that can be used with tuples. The not in operator returns True if the first operand is not contained within the second, and False otherwise.'one' not in a
False
Method | Description |
---|---|
index(m,a(optional),b(optional)) | the index of first occurrence of m for a given substring indicated by a and b |
count(m,a(optional),b(optional)) | number of occurrences of m within the substring indicated by a and b |
a.index(23)
1
a.count('one')
1
To be honest, tuples are not used as often as lists in programming, but are used when immutability is necessary. If in your program you are passing around an object and need to make sure it does not get changed, then a tuple becomes your solution. It provides a convenient source of data integrity.
b = ([1,'hello'], (26.3, 56))
print(b)
([1, 'hello'], (26.3, 56))
b[0][1]
'hello'
b[1][1]
56