Tuples

Tuples and Lists ... you can just watch the tuple portion.

Strings and Lists are basic iterable data types that are very similar with key differences:

  • Strings only allow alphanumeric characters and special symbols to represent text

  • Lists allow all data types as its items/members

  • Strings are immutable whereas Lists are mutable

These significant differences cause a headache when you require the following data structure:

  • It must be immutable

  • It must allow different datatypes as items

  • It must be iterable

  • It must be nestable (much like a list within a list)

All of these are solved with a data structure called: Tuple.

How to use Tuples in Python 3

  • Tuples are declared with parenthesis … aka round brackets

  • () is an empty tuple

  • (50,) is a singleton tuple; the comma is required

  • Tuples are sliceable; therefore, indexable using square brackets

A singleton is an iterable data structure with only single item.

Tuple Example 1

Tuple Operators

Tuples are Iterable, Indexable, and Sliceable

Built-in Functions with Tuple

Tuple Comprehension

The parentheses were taken for a different functionality in python; therefore, we have to do comprehension like this.

The general format is the exactly the same as list comprehension.

Tuple & Python: Packing and Unpacking

Explanation:

  • Packing collect multiple variable’s values and assign it to a single variable

  • Unpacking help us assign certain values from a tuple to different variables

  • This becomes very useful skill when combined with variable arguments for Function Definition and Function Calls

Last updated