Tuples
instance of tuple class. it is ordered sequence of elements. it is immutable. duplicate elements allowed.
create a tuple
use () or tuple() to create a tuple.
python
color = ('red', 'green', 'blue')
transport = tuple(('car', 'plane', 'train'))
# note the double parentheses
msg_pref = 'email', 'text', 'phone'
# without parenthesesaccess elements
use tuple[index] to access elements. negative index available.
python
print(color[1])
# green
print(transport[-1])
# trainchange element
Not possible. TypeError will returned
delete element
not possible. TypeError will returned
tuples of dictionary
dict element can be changed inside tuple as they are mutable.
python
users = (
{'name': 'John', 'age': 23},
{'name': 'Jane', 'age': 25}
)
users[0]['age'] = 24
print(users)
# ({'name': 'John', 'age': 24}, {'name': 'Jane', 'age': 25})non existance element
will return IndexError if you try to access non-existance element.
combine tuple
use + operator to combine tuple. it create new tuple but original tuple remained unchanged.
python
new_tuple = color + transport
print(new_tuple)
# ('red', 'green', 'blue', 'car', 'plane', 'train')methods
just 2 methods
count()- return the count of matched element.index()- return index of first matched element.
python
plane_count = transport.count('plane')
print(plane_count)
# 1
train_index = transport.index('train')
print(train_index)
# 2what if I need to modify tuple?
first convert it to list, modify it, and then convert to tuple.
python
color_list = list(color)
color_list[1] = 'yellow'
color = tuple(color_list)
print(color)
# ('red', 'yellow', 'blue')