liveBook · Manning

One-element tuple

As explained in Get Programming: Learn to code with Python

A singleton tuple is a tuple containing exactly one element and indicated by a trailing comma.

A one-element tuple, also called a singleton tuple, contains exactly one object. Write a trailing comma inside the parentheses: (5,). The comma creates the tuple; parentheses alone do not. section 10.1

Adding one word to a tuple

In a Scrabble word search, all_valid_words = all_valid_words + (words[start:end],) adds one newly found word to the existing tuple. The comma is required because the extracted word is a single element. section 19.2

Compare these tuple forms:

  • () is an empty tuple; (1, 2, 3) contains three objects; ("tickets") is just a parenthesized string; ("carnival",) is a singleton tuple. section 10.1
  • A singleton tuple can also hold a value while building a larger tuple, as in found_words = found_words + (word,). section 19.2

How Get Programming: Learn to code with Python covers it

How deep it goes
Defines the trailing-comma rule, contrasts similar forms, and demonstrates tuple concatenation without descending into implementation internals.
Examples
Demonstrates singleton tuples with numbers, carnival tickets, Scrabble words, and names or phone numbers read from a file.
What you can do after
Build tuple values containing one newly discovered or parsed object, and distinguish them from parenthesized expressions.
How it connects
Connects singleton tuples to tuples, tuple concatenation, string parsing, and file parsing.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Get Programming: Learn to code with Python. The section links point to the parts of the book it draws on.