Python tuple() Function
tuple() is a built-in function in Python used to convert a sequence into a tuple.
A tuple is an immutable sequence type; once created, it cannot be modified.tuple() The function can convert iterables such as lists, strings, dictionaries and sets into tuples.
Word meaning: tuple means "tuple" and is an immutable sequence type in Python.
Basic syntax and parameters
Syntax format
tuple(iterable)
Parameter Description
- Parameter iterable:
- Type: iterable (list, string, dictionary, set, etc.)
- Description: the iterable to convert into a tuple.
Function description
- Return Value: Returns a tuple.
- Special values: Called without arguments it returns an empty tuple
()。
Example
Example 1: converting from a list
Example
Convert a list into a tuple
lst
=
[
1
,
2
,
3
,
4
,
5
]
t
=
tuple
(
lst
)
(
t
)
Output: (1, 2, 3, 4, 5)
(
type
(
t
)
)
Output:
Convert from a string (each character becomes an element)
s
=
"hello"
t
=
tuple
(
s
)
(
t
)
Output: ('h', 'e', 'l', 'l', 'o')
Convert from a dictionary (keys only)
d
=
{
"a"
:
1
,
"b"
:
2
}
t
=
tuple
(
d
)
(
t
)
Output: ('a', 'b')
Convert from a set
s
=
{
1
,
2
,
3
}
t
=
tuple
(
s
)
(
t
)
Output: (1, 2, 3) (the order may vary)
Empty tuple
t
=
tuple
(
)
(
t
)
Output: ()
Expected output:
(1, 2, 3, 4, 5)
('h', 'e', 'l', 'l', 'o')
('a', 'b')
(1, 2, 3)
()
Code analysis:
- Converting a list into a tuple preserves the element order.
- When converting a string, each character becomes an element of the tuple.
- Converting a dictionary includes only the keys, not the values.
Example 2: features of tuples
Example
Tuples are immutable
t
=
(
1
,
2
,
3
)
t[0] = 10 # this raises TypeError
Can be used as dictionary keys
d
=
{
(
1
,
2
)
:
"point"
,
(
3
,
4
)
:
"origin"
}
(
d
)
Output: {(1, 2): 'point', (3, 4): 'origin'}
Can be nested
t
=
(
(
1
,
2
)
,
(
3
,
4
)
)
(
t
)
Output: ((1, 2), (3, 4))
Tuple unpacking
a
,
b
,
c
=
(
1
,
2
,
3
)
(
f
"a={a}, b={b}, c={c}"
)
Output: a=1, b=2, c=3
Expected output:
{(1, 2): 'point', (3, 4): 'origin'}
((1, 2), (3, 4))
a=1, b=2, c=3
Tuples are immutable, can be used as dictionary keys and support unpacking.
Python3 built-in function