Tuesday, March 29, 2022

Tuples

Tuples are usually used for a small number of entries and when the position and sequence of the entries in a collection is important. To preserve the sequence of entries, tuples are designed as immutable, and this is where tuples differentiate themselves from lists.

Operations on a tuple are typically faster than a regular list datatype. In cases when the values in a collection are required to be constant in a particular order, using tuples is the preferred option because of their superior performance.

Tuples are normally initialized with values because they are immutable. A simple tuple can be created using parenthesis. A few ways to create tuple instances are shown in the next code snippet:

w = () #an empty tuple
x = (2, 3) #tuple with two elements
y = ("Hello World") #not a tuple, Comma is required \ for single entry tuple
z = ("Hello World",) #A comma will make it a tuple

In this code snippet, we created an empty tuple (w), a tuple with numbers (x), and a tuple with the text Hello World, which is z. The variable y is not a tuple since, for a 1-tuple (a single-object tuple), we need a trailing comma to indicate that it is a tuple.

After introducing lists and tuples, we will briefly introduce dictionaries in the next post

Share:

0 comments:

Post a Comment