Tuples
Tuples
Data Types
A tuple can contain different data types:
Negative Indexing
Starting from the end.
o -1 last item,
o -2 second last item etc.
Slicing
Ranges of Indexes
o where to start and where to end the
range.
o new tuple with the specified items
will be returned.
Update Tuples
Tuples are unchangeable,
o meaning that you cannot change,
add, or remove items once the tuple
is created.
But there are some workarounds. i.e.
i. convert the tuple into a list(changeable),
ii. change the list,
iii. convert back to a tuple. (type
casting)
e.g. insert another item to the tuple, X
Add Items
Since tuples are unchangeable,
o they do not have a built-in append()
method,
So to do it,
i. Convert into a list,
ii. Use append () on the list
iii. convert it back into a tuple.
e.g. append item to tuple, X
Remove Items
Note: You cannot remove items in a
tuple.
Tuples are unchangeable,
so you can use the same workaround
as we used for changing and adding
tuple items:
Unpack Tuples
When we create a tuple,
o we normally assign values to it,
called "packing" a tuple: e.g.
o fruits = ("apple", "banana", "cherry")
We can also extract the values back and
store the values into individual variables.
o This is called "unpacking":
Tuple Methods
.count() Method
Return the number of times a value appears
in the tuple. E.g. 5
.index() Method
Returns position of first occurrence of a
value,
E.g. index of 8 will be 3