10. Python Tuples

Tuple is one of Python's data structures which is ordered values. Tuples are defined with brackets. Example

subjects = ('math', 'biology', 'chemistry')
mix_type_tuple = (123, 34.5, 'This is string', 23 + 9j)
fruits = ('banana', 'grape', 'watermelon', 'mango', 'apple')
numbers = (1, 2, 3, 4, 5)

10.1 Accessing Tuples

To access values in tuple, use the square brackets with this expression tuple_name[start_index:end_index:step] for slicing along with the index or indices to obtain value available at that index. Example

subjects = ('math', 'biology', 'chemistry')
numbers = (1, 2, 3, 4, 5, 6, 7, 8)
words = ('Python', 'is', 'awesome', 'yeah')

print('subjects[0]:', subjects[0]);     # indexing
print('numbers[2:5]:', numbers[2:5])    # slicing
print('numbers[::2]:', numbers[::2])    # by default start index is 0 and end index is the length of list
print('numbers[2:7:2]', numbers[2:7:2]) 
print('words[-2]:', words[-2:])         # negative index count from the right
print('numbers[:]:', numbers[:])

10.2 Update the Tuples

Unlike lists tuple is immutable which means you cannot update or change and delete specific values of tuple by using del keyword, but you can create new tuples from existing tuples.

>>> subjects = ('math', 'biology', 'chemistry')
>>> words = ('Python', 'is', 'awesome', 'yeah')
>>> new_tuple = subjects + words
>>> new_tuple = subjects + words # this is OK
>>> subjects[0] = 'algebra'  # but this will generate error
Traceback (most recent call last):
  File "<pyshell#4>", line 1, in <module>
    subjects[0] = 'algebra'  # but this will generate error
TypeError: 'tuple' object does not support item assignment
>>> del subjects[0]    # this will generate error too
Traceback (most recent call last):
  File "<pyshell#5>", line 1, in <module>
    del subjects[0]    # this will generate error too
TypeError: 'tuple' object doesnt support item deletion
>>> del subjects  # this is OK
>>> print(subjects)   # this will generate error
Traceback (most recent call last):
  File "<pyshell#7>", line 1, in <module>
    print(subjects)   # this will generate error
NameError: name 'subjects' is not defined

10.3 Tuples Operations

Some operations tuples can do are concatenation, repetition, membership, identity, and iterate over the tuple.

>>> (1, 2, 3) + (4, 5, 6) # concatenation
(1, 2, 3, 4, 5, 6)
>>> ('Hello') * 3 # repetition
'HelloHelloHello'
>>> 2 in (1, 2, 3) # membership
True
>>> (1, 2, 3) is (3, 4, 5) # identity
False
>>> for num in (3, 4, 5): # iterate over the tuple
 print(num)

 
3
4
5

That's all brief introduction about Python tuples, if you guys have any questions please give comments.


Subscribe to receive free email updates:

3 Responses to "10. Python Tuples"