3

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

8
  • 3
    You can pass any sequence as a parameter. Commented May 9, 2020 at 22:21
  • Nothing, really, just like there is little difference between list() and []. Commented May 9, 2020 at 22:21
  • 1
    Same as [] vs list and {} vs dict Commented May 9, 2020 at 22:21
  • 1
    tuple is the type itself, and like other container types, it can take an iterable as an argument to populate the new instance when called. Commented May 9, 2020 at 22:22
  • 1
    Err, to construct a tuple. Is that so surprising? Commented May 9, 2020 at 22:33

3 Answers 3

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
Sign up to request clarification or add additional context in comments.

1 Comment

I'll just add here that usually you use tuple() when you already have some iterable and you want it as a tuple instead.
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',)

2 Comments

Ironically it's one less character to pass a list, tuple(['abc']) vs tuple(('abc',))
() isn't a constructor, literal notation isn't a constructor really
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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.