Tuples

A tuple is an immutable sequence, which means that its contents cannot be changed.

In [2]:
# example of tuples

my_tuple = (1,2,3,4,5)
print(my_tuple)
(1, 2, 3, 4, 5)
In [4]:
# use for loop to iterate over the elements in a tuple

names = ('Holly','Marry','Love')
for n in names:
    print(n)
Holly
Marry
Love
In [3]:
# tuples also support indexing

names = ('Holly','Marry','Love')
for i in range(len(names)):
    print(names[i])
Holly
Marry
Love
In [6]:
# tuple with one element
my_tuple = (1,)
print(type(my_tuple))

my_tuple = (1)
print(type(my_tuple))
<class 'tuple'>
<class 'int'>

Converting between lists and tuples

In [7]:
number_tuple = (1,2,3)
number_list = list(number_tuple)
print(number_list)
[1, 2, 3]
In [8]:
str_list = ['one','two','three']
str_tuple = tuple(str_list)
print(str_tuple)
('one', 'two', 'three')
In [ ]: