
Create or declare a tuple in Python
A Python tuple is the data type containing multiple elements like a list or dictionary. All elements are separated with a comma and enclosed in round brackets. Tuples are declared as follows.
a = (1, 2, 3)
b = ('pen', 'book')
print(a) # (1, 2, 3)
print(b) # ('pen', 'book')
Both variables are tuples. Empty tuple is created like this.
a = ()
print(a) # ()
print(type(a)) # <class 'tuple'>
You can write a trailing comma declaring a tuple. Basically the last comma doesn't mean there is another element.
a = (1, 2, 3,)
print(a) # (1, 2, 3)
The advantage of trailing commas can be found in the following code.
a = (
1,
2,
3,
)
print(a) # (1, 2, 3)
In Python programming, a value can be represented so long that it's better to align elements vertically than horizontally in a tuple or list. The trailing comma fits in the alignment meaning clearly the value is an element of a tuple.
Even if you like to use the trailing comma, it's good that you and your team are consistent with usage of it.
Comments
Powered by Markdown