Tuples in Python
Tuples in Python is a collection which is use to store multiple elements in a single variable. Tuple is a built-in data types in Python. There are many data types which can store multiple items as well as List, or Set or String . Indexing item in tuple is as same as List. Index 0 is the first item, 1 is the second item.
Tuples in Python is :
- Unchangeable: We can not change any item such as add, remove, and change after tuple was created.
- Allow duplicated: We can duplicated items in tuple.
- Ordered: The ordered items in tuple can not be changed. They’ve already defined.
It can be written as bracket (…) while List writes as [… ]
Tuple can be store any data type such Boolean, Integer, float… etc
how to create tuple
We can create tuple with one item. In this case, developer can be confuse, create one item in tuple must be with comma after. Otherwise, will confuse to String data type.
For example:
myCar=('Toyota')
myCar1=('Toyota',)
#not tuple
print(type(myCar))
#tuple
print(type(myCar1))
#output: <class 'str'>
# <class 'tuple'>
Tuple Constructor
We can create tuple class constructor to make tuple object from iterable Set, List, String and Dictionary.
- Syntax: tuple ([iterable])
For example:
myCar=(('Toyota','Mitsubishi',12,3,True))
print(myCar)
#output: ('Toyota', 'Mitsubishi', 12, 3, True)