Python tuple() Function
tuple()It 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 iterable objects such as lists, strings, dictionaries, and sets into tuples.
Word Meaning: tupleIt means "tuple", an immutable sequence type in Python.
Basic Syntax and Parameters
Syntax Format
tuple(iterable)
Parameter Description
- Parameter iterable:
- Type: iterable object (list, string, dictionary, set, etc.)
- Description: The iterable object to convert into a tuple.
Function Description
- Return Value: Returns a tuple.
- Special Value: Returns an empty tuple if no argument is given.
()。
Examples
Example 1: Converting from a List
Example
# Convert from a list to a tuple
lst = [1, 2, 3, 4, 5]
t = tuple(lst)
print(t) # Output: (1, 2, 3, 4, 5)
print(type(t)) # Output: <class 'tuple'>
# Convert from a string (each character as an element)
s = "hello"
t = tuple(s)
print(t) # Output: ('h', 'e', 'l', 'l', 'o')
# Convert from a dictionary (only keys are taken)
d = {"a": 1, "b": 2}
t = tuple(d)
print(t) # Output: ('a', 'b')
# Convert from a set
s = {1, 2, 3}
t = tuple(s)
print(t) # Output: (1, 2, 3) (order may differ)
# Empty tuple
t = tuple()
print(t) # Output: ()
lst = [1, 2, 3, 4, 5]
t = tuple(lst)
print(t) # Output: (1, 2, 3, 4, 5)
print(type(t)) # Output: <class 'tuple'>
# Convert from a string (each character as an element)
s = "hello"
t = tuple(s)
print(t) # Output: ('h', 'e', 'l', 'l', 'o')
# Convert from a dictionary (only keys are taken)
d = {"a": 1, "b": 2}
t = tuple(d)
print(t) # Output: ('a', 'b')
# Convert from a set
s = {1, 2, 3}
t = tuple(s)
print(t) # Output: (1, 2, 3) (order may differ)
# Empty tuple
t = tuple()
print(t) # Output: ()
Expected output:
(1, 2, 3, 4, 5)
<class 'tuple'>
('h', 'e', 'l', 'l', 'o')
('a', 'b')
(1, 2, 3)
()
Code explanation:
- Converting a list to a tuple preserves the order of elements.
- When converting a string, each character becomes an element of the tuple.
- Dictionary conversion only includes keys, not values.
Example 2: Characteristics of Tuples
Example
# Tuples are immutable
t = (1, 2, 3)
# t
# Can be used as dictionary keys
d = {(1, 2): "point", (3, 4): "origin"}
print(d) # Output: {(1, 2): 'point', (3, 4): 'origin'}
# Can be nested
t = ((1, 2), (3, 4))
print(t) # Output: ((1, 2), (3, 4))
# Tuple unpacking
a, b, c = (1, 2, 3)
print(f"a={a}, b={b}, c={c}") # Output: a=1, b=2, c=3
t = (1, 2, 3)
# t
# Can be used as dictionary keys
d = {(1, 2): "point", (3, 4): "origin"}
print(d) # Output: {(1, 2): 'point', (3, 4): 'origin'}
# Can be nested
t = ((1, 2), (3, 4))
print(t) # Output: ((1, 2), (3, 4))
# Tuple unpacking
a, b, c = (1, 2, 3)
print(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 operations.
Other Extensions