I recently came across tuple() as a constructor in python, if there exists a difference between just using () and tuple(), What is it?
3 Answers
tuple is a type.
>>> tuple
<class 'tuple'>
When you call the type, you can pass any kind of iterable to get back a non-empty tuple containing the elements of the iterable.
>>> tuple([1,2,3])
(1, 2, 3)
>>> tuple((1,2,3))
(1, 2, 3)
>>> tuple(i+1 for i in range(3))
(1, 2, 3)
If you don't pass an argument, you create an empty tuple.
>>> tuple()
()
() is a literal that evaluates to an empty tuple, just as if you had called the type with no argument.
>>> ()
()
>>> tuple() == ()
True
1 Comment
tuple() when you already have some iterable and you want it as a tuple instead.Really the biggest difference between using the literal constructor of () and tuple() is the behavior with iterable vs noniterable arguments.
With the literal representation, you can make a tuple like so:
>>> (1,2)
(1, 2)
You can represent that same tuple without the ():
>>> 1,2
(1, 2)
And a single element tuple, use a trailing comma:
>>> 1,
(1,)
>>> 'abc',
('abc',)
With the tuple function, the single argument must be iterable, and that can surprise at times:
>>> tuple('abc')
('a', 'b', 'c')
For a single element tuple element, you would think you can use a trailing comma, but that still may surprise with the function:
>>> tuple('abc',)
('a', 'b', 'c')
So you have to do:
>>> tuple(('abc',)) # or tuple(['abc'])
('abc',)
2 Comments
tuple(['abc']) vs tuple(('abc',))() isn't a constructor, literal notation isn't a constructor reallyIt's most useful for converting iterables to tuples. For example say you have a list of lists that you want to convert to a set. Well, lists aren't hashable, but tuples are*, so you can use the constructor to cast them:
set(map(tuple, list_of_lists))
or
set(tuple(x) for x in list_of_lists)
* Assuming they contain only hashable elements
list()and[].[]vslistand{}vsdicttupleis the type itself, and like other container types, it can take an iterable as an argument to populate the new instance when called.