Python tuple() Function

Python3 Built-in Functions


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: ()

Expected output:

(1, 2, 3, 4, 5)
<class 'tuple'>
('h', 'e', 'l', 'l', 'o')
('a', 'b')
(1, 2, 3)
()

Code explanation:

  1. Converting a list to a tuple preserves the order of elements.
  2. When converting a string, each character becomes an element of the tuple.
  3. 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

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.


Python3 Built-in Functions


Other Extensions