Borislav Hadzhiev
Last updated: Jul 2, 2022
Check out my new book
Use a trailing comma to convert a string to a tuple without splitting, e.g.
my_tuple = (my_str,)
. A tuple with one item is constructed by following a
value with a comma. Enclosing the value in parenthesis is not sufficient to
create a tuple.
my_str = 'one' my_tuple = (my_str,) print(my_tuple) # 👉️ ('one',) print(type(my_tuple)) # 👉️ <class 'tuple'> # -------------------- my_tuple_2 = my_str, print(my_tuple_2) # 👉️ ('one',) print(type(my_tuple_2)) # 👉️ <class 'tuple'>
We used a trailing comma to convert a string to a tuple without splitting.
If you pass the string to the tuple()
class, you'd get a tuple containing the
string's characters.
print(tuple('one')) # 👉️ ('o', 'n', 'e')
The tuple()
class takes an iterable (e.g. a list or a string) and creates a
tuple from it.
On the other hand, we can convert a string to a tuple by adding a trailing comma after the string.
As the
documentation
states construction of tuples with 1
item is done by following a value with a
comma.
For example, both of these variables store a tuple with 1 item only.
my_str = 'one' my_tuple = (my_str,) my_tuple_2 = my_str,
It is not sufficient to wrap a single value in parenthesis to create a tuple.
The trailing comma after the value is the difference between creating a tuple (with trailing comma) or creating a value of a different type (without trailing comma).
my_tuple_1 = ('one',) print(my_tuple_1) # 👉️ ('one',) print(type(my_tuple_1)) # 👉️ <class 'tuple'> my_str = ('one') print(my_str) # 👉️ 'one' print(type(my_str)) # 👉️ <class 'str'>
The first example uses a trailing comma after the value, so we end up creating a tuple.
The second example simply encloses a value in parenthesis, so we end up creating a string.
Tuples are constructed in multiple ways:
()
creates an empty tuplea,
or (a,)
a, b
or (a, b)
tuple()
constructorThe same syntax should be used when creating a list of tuples or using tuples as dictionary keys or values.
my_list = [('one',), ('two',), ('three',)] print(my_list[0]) # 👉️ ('one',) print(type(my_list[0])) # 👉️ <class 'tuple'>
Alternatively, you can use the tuple
class if you don't like the implicit
behavior of creating a tuple with a trailing comma.
my_str = 'one' my_tuple = tuple([my_str]) print(my_tuple) # 👉️ ('one',)
tuple()
class.This is important because had we passed a string to the class, we would get a tuple containing the string's characters.
If you aren't sure what type a variable stores, use the built-in type()
class.
my_str = 'one' print(type(my_str)) # 👉️ <class 'str'> print(isinstance(my_str, str)) # 👉️ True my_tuple = (my_str,) print(type(my_tuple)) # 👉️ <class 'tuple'> print(isinstance(my_tuple, tuple)) # 👉️ True
The type class returns the type of an object.
The isinstance
function returns True
if the passed in object is an instance or a subclass of
the passed in class.