Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

Python3 tuple Function

Python tuple() Function

Python3 Built-in Functions Python3 built-in 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

- Type: iterable (list, string, dictionary, set, etc.) - Description: the iterable to convert into a tuple.

Function description


Example

Example 1: converting from a list

Example

Convert a list into a tuple

lst

=

[

1

,

2

,

3

,

4

,

5

]

t

=

tuple

(

lst

)

print

(

t

)

       

Output: (1, 2, 3, 4, 5)

print

(

type

(

t

)

)

 

Output:

Convert from a string (each character becomes an element)

s

=

"hello"

t

=

tuple

(

s

)

print

(

t

)

       

Output: ('h', 'e', 'l', 'l', 'o')

Convert from a dictionary (keys only)

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) (the order may vary)

Empty tuple

t

=

tuple

(

)

print

(

t

)

       

Output: ()

Expected output:

(1, 2, 3, 4, 5)

('h', 'e', 'l', 'l', 'o')
('a', 'b')
(1, 2, 3)
()

Code analysis:

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

}

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.


Python3 Built-in Functions Python3 built-in function