1

Can anyone give me an example of why I would need to create/use an empty tuple and why it would be considered useful? I understand tuples are immutable and created using ().

Apoorv Kansal
  • 3,210
  • 6
  • 27
  • 37
jasmine
  • 361
  • 1
  • 3
  • 11
  • Is there any similar usage pattern you came across which led to this question? – bashrc Dec 02 '16 at 06:10
  • 4
    http://stackoverflow.com/questions/4828041/are-there-any-uses-of-the-empty-tuple-in-python – Apoorv Kansal Dec 02 '16 at 06:11
  • 2
    You might have a function that iterates over an iterable, like a list or tuple. It might be easier to pass an empty tuple, such that looping over it does nothing, instead of adding special logic to handle None – Jacob Panikulam Dec 02 '16 at 06:12
  • You can start with an empty tuple as an accumulator and "add" values to it in a loop. Same as with an empty string. – DYZ Dec 02 '16 at 06:15
  • @DYZ -- Surely a `list` is a more appropriate data structure for that case ... – mgilson Dec 02 '16 at 06:16
  • @mgilson Surely. But the OT wanted an example of an empty tuple use. – DYZ Dec 02 '16 at 06:18
  • You can use an empty `tuple()` as a sentinel, e.g.: `for chunk in iter(lambda: tuple(it.islice(iterable, length)), tuple()):` – AChampion Dec 02 '16 at 06:18
  • 2
    One place that I find myself using this is when creating default arguments for functions: `def foo(sequence=()): ...`, We don't want to use a list here because then you get into the "mutable default argument" badness, we could use `None`, but then we need to check before we do any sequence operations on it (e.g. iterating). An empty tuple supports sequence operations _and_ it's immutable so we're golden... – mgilson Dec 02 '16 at 06:19

0 Answers0