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))
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')
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.