Some time ago I thought that the tuple's constructor was a pair of parentheses ()
.
Example:
>>> (1, )
(1, )
>>> type((1, ))
<type 'tuple'>
>>> t = (1, )
>>> type(t)
<type 'tuple'>
But now I know that it is the comma ,
.
So, doing the same as above:
>>> 1,
(1,)
>>> type(1,)
<type 'int'> # Why?
>>> 1,2,3
(1,2,3)
But if I do:
>>> type(1,2,3)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: type() argument 1 must be string, not int
This makes sense to me, but:
>>> t = 1,2,3
>>> type(t)
<type 'tuple'>
And finally:
>>> type((1,2,3))
<type 'tuple'>
Here's the question: why are parenthesis needed in the final case if the tuple is just 1,2,3
?
In Python, tuples is just a comma-separated sequence which can be created with or without parentheses () .
The use of a double parentheses is actually an indicator of one of Python's coolest features - and that is that functions are themselves, objects! What does this mean? Our output is an integer, with a value of 3.
Tuples A Tuple represents a collection of objects that are ordered and immutable (cannot be modified). Tuples allow duplicate members and are indexed. Lists Lists hold a collection of objects that are ordered and mutable (changeable), they are indexed and allow duplicate members.
Creating a TupleThe parentheses are optional, however, it is a good practice to use them. A tuple can have any number of items and they may be of different types (integer, float, list, string, etc.). A tuple can also be created without using parentheses.
In some contexts, commas have another meaning - for example, inside the parentheses of a function call, they separate the parameters. Putting a set of parentheses around your tuple guarantees that it's in a simple expression context, where the commas are interpreted as tuple element separators.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With