Python: Tuple
Tuple is like a list, except that it cannot be changed. The element values are fixed, the length is also fixed.
Create Tuple
tuple(iterable)
-
Return a new tuple with elements of iterable.
Example:
tuple([3,4,5])
Tuple can also be created by:
()
- Empty tuple.
(a,)
- Tuple with 1 element a.
(a, b, c)
- Tuple with element a, b, c.
a,
- Tuple with 1 element a.
a, b, c
- Tuple with element a, b, c.
x = tuple([3,4,5]) y = 3,4,5 print(x) # (3, 4, 5) print(y) # (3, 4, 5) print(x == y) # True
Tuple Cannot Change
Tuple cannot be changed, not element, and not length.
# tuple cannot be changed my_list = [3, 4, 5] my_tuple = (3, 4, 5) my_list[0] = 9 my_tuple[0] = 9 # TypeError: 'tuple' object does not support item assignment print(my_list) print(my_tuple)
Nested Tuple and List
List and tuple can contain mixed datatypes, and nested in anyway.
# list and tuple can contain mixed datatypes, and nested in anyway my_list = [3, "4", [11, "12"], ("a", 2), 5] my_tuple = (3, "4", [11, "12"], ("a", 2), 5) print(my_list) # [3, '4', [11, '12'], ('a', 2), 5] print(my_tuple) # (3, '4', [11, '12'], ('a', 2), 5)