bhylu.com

Advertisements

Python Tuples

A tuple is an ordered immutable container. It is useful for a small fixed record or an immutable sequence whose positions have a documented meaning.

Understand the idea

The comma creates a tuple; parentheses often make it easier to read. A one-item tuple needs a trailing comma. Immutability applies to the tuple's references, not necessarily to mutable objects stored inside it. Named records may be clearer than positional tuples as the number of fields grows.

Where to try it

Open this example with Try in playground. The code loads as editable text and does not run until you select Run. The first run downloads Python. Each run starts fresh; temporary files created by a script are not files on your PC.

A worked example

Python

location = ("Nadiad", 12)
single = ("Python",)
print(location[0], len(single))

Read the result

The output is Nadiad 1. single contains one string rather than being the string itself.

Try one change

Create a two-field tuple describing a workshop and explain what each position means.