Python: Tuple
What is Tuple
Tuple is like a List , except that it cannot be changed. Items cannot change, length cannot change.
Create Tuple by Literal Expression
()
- Empty tuple.
(a,)
- Tuple with 1 item a.
(a, b, c)
- Tuple with item a, b, c.
a,
- Tuple with 1 item a.
a, b, c
- Tuple with item a, b, c.
Convert Iterable to Tuple
tuple(iterable)
-
Return a new tuple with items of iterable.
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 item, and not length.
# tuple cannot be changed xx = (3, 4, 5) xx[0] = 9 # TypeError: 'tuple' object does not support item assignment
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 xx = [3, "4", [11, "12"], ("a", 2), 5] yy = (3, "4", [11, "12"], ("a", 2), 5)
Python, Data Structure
- Python: List
- Python: Generate List: range
- Python: List Comprehension
- Python: List Methods
- Python: Iterate List
- Python: Map f to List
- Python: Filter List
- Python: Iterator to List
- Python: Copy Nested List, Shallow/Deep Copy
- Python: Interweave Lists to Tuples, Transpose
- Python: Sort
- Python: Convert List to Dictionary
- Python: Dictionary
- Python: Iterate Dictionary
- Python: Dictionary Methods
- Python: Tuple
- Python: Sets, Union, Intersection
- Python: Sequence Types
- Python: Read Write JSON