Tuple
A tuple is an immutable list. A tuple cannot be modified in any way once it has been created.
Why are tuples needed?
- In the case of protecting any data from changes (intentional or accidental).
- Tuples take up less memory space and are faster than lists.
- To return multiple values from a function.
- Tuples can be used as dictionary keys (more on that later).
Creating tuples
1 way: like a list, but with parentheses
1
2
3
|
a = (1,2,3,4,5)
print(type(a)) # class 'tuple'
print(a) # (1, 2, 3, 4, 5)
|
2 way: using
tuple()
function
1
2
3
|
b = tuple((1,2,3,4,5))
print(type(b)) # <class 'tuple'>
print(b) # (1, 2, 3, 4, 5)
|
You have to remember!
- Tuples are an immutable list.
- The elements of a tuple can be of different types.
- You can create a tuple using the
tuple()
function or by listing the elements in parentheses.