web-profile

Python Tuple

Python tuple is immutable.
Python tuple is similar to lists.

empty_tuple = ()
empty_tuple_2 = tuple()

pets = ('dog', 'cat', 'parrot')

print(pets) # ('dog', 'cat', 'parrot')

print(len(pets)) # 3

print('Slicing the tuple:')

print(pets[0]) # dog (Get first element)

print(pets[-1]) # parrot (Get last element)

print(pets[0:2]) # ['dog', 'cat'] (Get first two elements)
print(pets[:2]) # ['dog', 'cat'] (Get first two elements)

print(pets[-2:]) # ['cat', 'parrot'] (Get last two elements)

print('Get index of the element in the tuple:')
print(pets.index('dog')) # 0


print('Check if element is in the tuple:')
print('cat' in pets) # True
print('horse' not in pets) # True

print('Loop thru items in the tuple:')
for pet in pets:
    print('Pet item:', pet)

print('Loop thru items in the tuple with getting element index:')
for pet_index, pet_name in enumerate(pets): # enumerate(pets, start=1) to start from 1
    print('Pet index:', pet_index, ' pet name:', pet_name)

print('Join tuple items into a string:')
pets_str = '; '.join(pets)
print(pets_str) # dog; cat; parrot

print('Split string into tuple:')
pets_tuple = tuple(pets_str.split('; '))
print(pets_tuple) # ('dog', 'cat', 'parrot')


# You can unpack tuples (or lists) into variables
a, b, c = (1, 2, 3)  # a is now 1, b is now 2 and c is now 3
# You can also do extended unpacking
a, *b, c = (1, 2, 3, 4)  # a is now 1, b is now [2, 3] and c is now 4
# Tuples are created by default if you leave out the parentheses
d, e, f = 4, 5, 6
# Now look how easy it is to swap two values
e, d = d, e  # d is now 5 and e is now 4

Leave a Reply

Your email address will not be published.