Search notes:

Python: tuple

A tuple is an immutable sequence type. It stores references to objects which also makes it a container.

Creating tuples

A tuple is created from a sequence of expressions that are separated by commas.
tup = 4 * 2, 'foo', None
A trailing comma is permitted:
tup = 'one', 2, ['*', '*', '*'],
In order to create an empty tuple, empty parentheses are required:
tup = ()
In order to create an empty tuple, empty parentheses are required:
In order to create a tuple with one single element, either the parentheses or the trailing comma is required:
t1 = ( 42 )
T1 =   42 ,
The following simple Python script creates a few tuples and uses isinstance() to verify that the objects are indeed tuples:
empty_tuple            = ()
tuple_with_one_element = 'one',  # note the trailing comma
tup_1_2                =  1, 2
tup_X                  =  1, 2,  # another trailing comma

for t in [ empty_tuple, tuple_with_one_element, tup_1_2, tup_X]:
    if not isinstance(t, tuple):
       print('wrong assumption for', str(t), ', type is', type(t))
Github repository about-Python, path: /types/tuple/create.py
Note, the var1, var2, var3 is used for a different purpose in sequence unpacking.

Creating a tuple from a string

When a tuple is created from a string, the characters of the string become the elements in the tuple:
t = tuple('hello')

print(t)
#
# ('h', 'e', 'l', 'l', 'o')
Github repository about-Python, path: /types/tuple/create-from-string.py
This is because a string is an iterable and the tuple's constructor constructs the tuple from the elements that an iterable returns.
The same is also the case for list.

See also

Comparing tuples with lists
The collections module.
collections.namedtuple
Other Built-in types

Index