3

I recently came across tuple() as a constructor in python, if there exists a difference between just using () and tuple(), What is it?

Zeeshan ahmed
  • 121
  • 1
  • 4

3 Answers3

6

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
chepner
  • 497,756
  • 71
  • 530
  • 681
  • 3
    I'll just add here that usually you use `tuple()` when you already have some iterable and you want it as a tuple instead. – DragonBobZ May 09 '20 at 22:37
3

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',)
dawg
  • 98,345
  • 23
  • 131
  • 206
1

It'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

wjandrea
  • 28,235
  • 9
  • 60
  • 81