Python Reference ยท Built-in Functions
Python tuple() function
Reference for Python tuple(): create immutable sequences from any iterable, single-item tuples, hashing, shallow immutability and when to prefer lists.
tuple is Python's immutable sequence type, and tuple(iterable) builds one from any iterable. Once created, a tuple cannot be changed: you cannot add, remove or reassign items. That makes tuples a good fit for fixed records such as coordinates, return values with several parts and dictionary keys.
Most tuples are written as literals: (1, 2, 3) or just 1, 2, 3. The constructor is useful for converting other iterables, such as lists, strings and generators.
tuple([1, 2, 3]) # (1, 2, 3) tuple("abc") # ('a', 'b', 'c')
Try it
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.
Syntax
tuple() tuple(iterable)
| Name | Description |
|---|---|
iterable |
Optional. Any iterable; its items become the tuple's items in iteration order. |
Return value: a new tuple. If the argument is already a tuple (not a subclass), tuple(t) returns the very same object.
Raises: TypeError if the argument is not iterable.
Usage notes
- The comma makes the tuple, not the parentheses. A one-item tuple needs a trailing comma:
(5,). - Shallow immutability. The tuple's references cannot change, but a mutable item inside (a list) still can.
- Hashable if all items are. Tuples of numbers, strings and other tuples can be dictionary keys or set members; tuples containing lists cannot.
- Comparison is lexicographic, item by item, and tuples sort that way too.
- Unpacking. Tuples are what multiple return values and
for k, v in d.items()are built on. See unpacking. - Slightly smaller and faster than lists to create and iterate, though the difference rarely matters.
- Methods: only
count()andindex(); see tuple methods. - Generators are consumed completely by
tuple(gen); infinite ones never finish. - Named fields come from
collections.namedtupleortyping.NamedTuple.
Related
list(),set(),frozenset(),zip(),tuple methods- Lessons: Tuples, Unpacking