PythonBuilt-in functions
tuple()
Creates a tuple: an immutable sequence of items.
- Returns
- A new tuple.
Example
#Python
point = (3, 4)
print(point[0], len(point))
print(tuple([1, 2, 3]))
print(type(("html",)), type(("html")))
try:
point[0] = 10
except TypeError as error:
print(error)Resultsaved result, you can check it
3 2
(1, 2, 3)
<class 'tuple'> <class 'str'>
'tuple' object does not support item assignment
Definition and usage
#The tuple() function creates a tuple from an iterable. A tuple behaves like a list, but once created it can't be changed: you can't add, remove, or replace items.
Immutability has its advantages: a tuple can be a dictionary key and a set element, and using one signals that the data is fixed, like the coordinates of a point or a row from a database.
Tuples are usually created with parentheses: (3, 4). A one-item tuple needs a comma: ("html",), because parentheses alone just group an expression.
Syntax
#Syntax
tuple()
tuple(iterable)Parameters
#iterable
optional
The items of the new tuple.
Good practices
#- Remember the comma in a one-item tuple:
(x,). - A function that returns several values (
return a, b) returns a tuple, which you can conveniently unpack.
Related entries
#- list vs tuplelist is a mutable sequence you can modify, while tuple is an immutable sequence that can be a dictionary key or a set element.
- list()Creates a list, either empty or from the items of another iterable.
- Unpacking sequencesAssigning the items of a tuple or list to several variables at once.
- dict()Creates a dictionary from key-value pairs or keyword arguments.
- set()Creates a set: an unordered collection of unique items.
Spotted a mistake or missing an example? Write to us.