#!/usr/bin/python3 # -*- coding: utf-8 -*- """ Tuples are immutable ordered sequences of vaules, which may be potentially heterougenous and/or nested. """ from typing import Tuple help(tuple) # %% Tuples are like lists but are immutable (not changeable). pointlessemptytuple = () # We can't add values to it... but we could create a new one from it: pointless_addition: Tuple[int, int] = pointlessemptytuple + (1, 2) # https://stackoverflow.com/questions/47533787/typehinting-tuples-in-python pointless_addition2: Tuple[int, ...] = pointlessemptytuple + (1, 2) # Tuples store ordered values, that may repeat, or be heterogenous (like lists). tup: Tuple[int, int, int, int] = (1, 2, 3, 3) print(tup[0]) # => 1, the first element print("Type: tup[0] = 3") # Raises a TypeError: # tup[0] = 3 # Raises a TypeError: # TypeError: 'tuple' object does not support item assignment # ACTUALLY READ THE ERRORS # Note that in making a tuple of length one, # it has to have a comma after the last element, # but tuples of other lengths, even zero, do not. print(type((1))) # => print(type((1,))) # => print(type(())) # => # You can perform most list operations on tuples too print(len(tup)) print(tup + (4, 5, 6)) # => (1, 2, 3, 3, 4, 5, 6) print(tup[:2]) # => (1, 2) print(2 in tup) # => True print(2 not in tup) # => True # Lists are mutable, so tuples don't have those functions. # You can unpack tuples (or lists) into variables a, b, c = (1, 2, 3) # a is now 1, b is now 2 and c is now 3 # You can also do extended unpacking (more to come later) x, *y, z = (1, 2, 3, 4) # a is now 1, b is now [2, 3] and c is now 4 # Tuples are created by default if you leave out the parentheses d, e, f = 4, 5, 6 # tuple 4, 5, 6 is created before being fed to the operator= # and then unpacked into variables d, e and f # respectively such that d = 4, e = 5 and f = 6 # Now look how easy it is to swap two values e, d = d, e # d is now 5 and e is now 4 # The alternative is to that swap is, in general to use a third temp variable: temp = e e = d d = temp # Tuples are like lists in that they can be heterogeneous mytuple: Tuple[str, int, float, str, float] = ("abcd", 786, 2.23, "john", 70.2) tinytuple: Tuple[int, str] = (123, "john") # Discuss: what's up with those type hints? # What are tuples usually used for? # They're typically short consistent ordered value groups, # like a 2-tuple (x, y) print(mytuple) # Prints complete tuple print(mytuple[0]) # Prints first element of the tuple print(mytuple[1:3]) # Prints elements starting from 2nd till 3rd print(mytuple[2:]) # Prints elements starting from 3rd element print(tinytuple * 2) # Prints tuple two times print(mytuple + tinytuple) # Prints concatenated tuple # Printing tuples returned_tuple: Tuple[str, int] = ("the answer", 42) print(type(returned_tuple)) print(returned_tuple) stringified: str = str(returned_tuple) # convert the tuple to string print(type(stringified)) print(stringified)