[ad_1]
Python has several sequential data types that allow you to store collections of data in an organized and efficient way. The basic sequence types are strings, lists, tuples, and range objects.
This article will walk you through the basics of Python tuples. We’ll show you how to create a tuple, access elements, unpack a tuple, and more.
Tuples are similar to lists
, with the main difference being that the lists are mutable while the tuples are immutable. This means that the tuples can not be changed after creation.
Tuples can store both heterogeneous and homogeneous data but are generally used to store collections of heterogeneous elements.
Creating Tuples
Tuples are created by placing the items inside a pair of round brackets []
, separated by commas. They can have any number of items, which can be of different types. Here is an example:
colors = ('orange', 'white', 'green')
A tuple can have items with mixed data types. You can also declare nested tuples where one more more of its items are lists, tuples or dictionaries:
my_tuple = (1, False, ["red", "blue"], ("foo", "bar"))
Round brackets with no elements in between them denote an empty tuple:
To create a tuple with only one element you must add a comma after the element:
my_tuple = (1)
type(my_tuple)
my_tuple = (1,)
type(my_tuple)
<class 'int'>
<class 'tuple'>
Tuples can be also constructed using the tuple()
constructor:
colors_list = ['orange', 'white', 'green']
colors_typle = tuple(colors_list)
print(type(colors_typle))
<class 'tuple'>
Another way to construct a tuple is to use the tuple packing feature, which allows you create a tuple from a sequence of comma-separated objects:
directions = "North", "South", "East", "West"
print(type(directions))
<class 'tuple'>
Accessing Tuple Elements
A tuple item can be referenced by its index. Indexes are integers and starts from 0
to n-1
where n
is the number of items:
my_tuple = ["a", "b", "c", "d"]
0 1 2 3
In Python indexes are specified with square brackets:
For example to access the third element of the tuple, you would tuple_name[2]
:
directions = ("North", "South", "East", "West")
directions[2]
'East'
If you reference an index that doesn’t exist, an IndexError
exception is raised:
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
IndexError: tuple index out of range
To access items in a nested tuple use multiple indexes:
my_tuple = (1, False, ["red", "blue"], ("foo", "bar"))
my_tuple[3][1]
'bar'
You can also access the tuple elements using negative indexes. The last item is referred to as -1
, the second last item as -2
and so on:
my_tuple = ("a", "b", "c", "d")
-4 -3 -2 -1
directions = ("North", "South", "East", "West")
directions[-2]
'East'
Slicing Tuples
In Python, you can slice a tuple and other sequential data types using the following form:
sequence[start:stop:step]
start
is the index at which the extraction begins. When a negative index is used, it indicates an offset from the end of the tuple. If this argument is omitted, slicing begins from index 0.stop
is the index before which to end extraction; the result doesn’t include the “stop” element. When a negative index is used, it indicates an offset from the end of the tuple. If this argument is omitted or greater than the length of the tuple, slicing goes to the end of the tuple.step
is an optional argument and specifies the step of the slicing. When not specified, it defaults to 1. If a negative value is used, the slice takes elements in reverse order.
The result of slicing a tuple is a new tuple containing the extracted elements.
The following forms are legal in Python:
T[:] # copy whole tuple
T[start:] # slice the tuple starting from the element with index "start" to the end of the tuple.
T[:stop] # slice the tuple starting from the begging up to but not including the element with index "stop".
T[start:stop] # slice the tuple starting from the element with index "start" up to but not including the element with index "stop".
stop"
T[::step] # slice the tuple with a stride of "step"
Below is an example of how to slice a tuple starting from the element with index 1 up to but not including the element with index 4:
vegetables = ('Potatoes', 'Garlic', 'Celery', 'Carrots', 'Broccoli')
vegetables[1:4]
('Garlic', 'Celery', 'Carrots')
Unpacking Tuples
Sequence unpacking in a Python feature that allows you to take assign sequence objects to variables. Here is an example:
colors = ('orange', 'white', 'green')
a, b, c = colors
print(a)
print(b)
print(c)
The values of the tuple elements according to their position, are assigned to the variables on the left:
orange
white
green
When unpacking tuples, the number of variables on the left side tuple must be the same as the number of the tuple elements. Otherwise, you’ll get a ValueError
exception.
colors = ('orange', 'white', 'green')
a, b = colors
ValueError: too many values to unpack (expected 2)
Unpacking is handy when a method or function returns a sequence of objects:
def square_area_circumference(side_lenght):
return side_lenght * side_lenght, side_lenght * 4
area, circumference = square_area_circumference(5)
print(area)
print(circumference)
25
20
Changing a Tuple
Since tuples are immutable data structures, we can not update them directly. You can not add, change, remove elements in tuples.
If you try to change a tuple element you’ll get TypeError
exception:
colors = ("orange", "white", "green")
colors[1] = "blue"
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'tuple' object does not support item assignment
Elements of a mutable tuple items can be changed. For example, if the tuple has a list as one of its elements, you can update the list elements:
my_tuple = (1, 2, [5, 6, 7])
my_tuple[2][1] = 4
print(my_tuple)
(1, 2, [5, 4, 7])
Tuple Length
The built-in len()
function returns the total number of items of a given object.
To find a length of a tuple, pass it as an argument to the len()
function:
Here is an example:
colors = ("orange", "white", "green")
lenght = len(colors)
print(lenght)
3
Iterating Through a Tuple
To iterate through all elements in a tuple, you can use the for
loop:
directions = ("North", "South", "East", "West")
for direction in directions:
print(direction)
North
South
East
West
If you need indexes, you have several methods at your disposal. The most common ways are to combine the range()
and len()
functions or to use the built-in enumerate()
function.
The example below shows how to retrieve the index and the value of each item in the tuple:
directions = ("North", "South", "East", "West")
for i in range(len(directions)):
print("Index {} : Value {}".format(i, directions[i]))
Index 0 : Value North
Index 1 : Value South
Index 2 : Value East
Index 3 : Value West
Instead of using the range(len(...))
pattern, you can use the enumerate()
function to loop over a tuple in a more Pythonic way:
directions = ("North", "South", "East", "West")
for index, value in enumerate(directions):
print("Index {} : Value {}".format(index, value))
Index 0 : Value North
Index 1 : Value South
Index 2 : Value East
Index 3 : Value West
Check if an Element Exists
To check whether an element exist in a tuple, you can use the in
and not in
operators:
colors = ("orange", "white", "green")
print("orange" in colors)
The output will be either True
or False
:
True
Here is another example using the if
statement
:
colors = ("orange", "white", "green")
if "blue" not in colors:
print("no")
else:
print("yes")
no
Tuple Methods
The tuple object accepts the following methods:
count(x)
– Returns the number of times ‘x’ appears in the tuple.index(x)
– Returns the position of the first occurrence of an element with a value of ‘x’.
Below is a simple example showing how to use the methods:
my_tuple = ("a", "s", "s", "q", "a", "n")
print(my_tuple.count('a'))
print(my_tuple.index('a'))
2
0
Conclusion
In Python, Tuples are immutable sequences of objects that can not be changed once created.
If you have any questions or feedback, feel free to leave a comment.
[ad_2]
Source link