Tuples

1 minute read

What is tuple

Tuple is an immutable type in Python, think of it is an immutable list.

How to create

# Using tuple()
tuple_1 = tuple('spam')
print(tuple_1)
>>> ('s', 'p', 'a', 'm')

# Simply using parantheses
tuple_2 = ('s', 'p', 'a', 'm')
print(tuple_2)
>>> ('s', 'p', 'a', 'm')

# No paranthese also work
tuple_2 = 's', 'p', 'a', 'm'
print(tuple_2)
>>> ('s', 'p', 'a', 'm')


# Single element tuple
tuple_3 = 'a',
print(tuple_3)
>>> ('a',)

Accessing

letters = 'a', 'b', 'c', 'd', 'e', 'f'
print(letters[1])
>>> b

print(letters[-1])
>>> f

Mutation not allowed

Since tuples are immutable, in-place change methods are unavailable and assignments do not work on tuple.

letters = 'a', 'b', 'c', 'd', 'e', 'f'
letters[1] = 'd'  -- Not allowed

Contains indexOf

letters = 'a', 'b', 'c', 'd', 'e', 'f'
print('a' in letters)
>>> True

print(letters.index('a'))
>>> 0

print('x' in letters)
>>> False

Named tuples

Named tuples are somewhat like what classes are but without additional behavior. It’s a way of organizing data.

from collections import namedtuple
rec = namedtuple('Record', ['name', 'age', 'job'])
person_1 = rec(name='Sherlock Holmes', age=30, job='Detective')
print(person_1)
>>> Record(name='Sherlock Holmes', age=30, job='Detective')

# Can even access values using keys just as in Map
print(person_1.age)
>>> 30

print(person_1.job)
>>> Detective

Iteration

letters = 'a', 'b', 'c', 'd', 'e', 'f'
for x in letters:
    print(x, end=' ')

Comments