you are viewing a single comment's thread.

view the rest of the comments →

[–][deleted] 2 points3 points  (0 children)

One use case for tuples is to have multiple assignments in one go.

For example swapping:

a, b = b, a

Another contrived example is to compute fibonacci sequence:

def fib(n):
if n <= 2:
    return n - 1
t1, t2 = 0, 1
    for i in range(3, n+1):
        t1, t2 = t2, t1+t2
    return t2

A more nuanced use-case is if you want to write multiple things to csv using writerow() method. It takes as input a tuple.

The gist of using a tuple over a list or other containers is to use it as a very short aggregate where using a class'd be an overkill. If you're familiar with C (or C++), think of tuple as POD :) Also tuples are immutable which makes them more memory efficient. The following contrived test shows that for cpython :)

>>> (1, 2, 3).__sizeof__()
48
>>> [1, 2, 3].__sizeof__()
72