:PROPERTIES:
:ID:       b9f392bd-bd45-4e9e-94ec-b19caedff86f
:mtime:    20220501143116
:ctime:    20220430122532
:END:
#+title: List vs tuple
#+filetags: :Optimisation:Python:

* Points communs
/list/ et /tuple/ sont des données de type /sequence/ :
 * L'ordre d'insertion des données est conservé (/ordered sets/),
 * Support des fonctions de concaténation, répétition, indexation et /slicing/,
 * Stockage de données hétérogèes (généralement homogènes)/

* Différences
 * Syntaxe ([] pour /list/, () pour /tuple/),
 * La /list/ est /mutable/, le /tuple/ /immutable/ (ne peut être modifié une fois créé),

** Empreinte RAM
 * Le /tuple/ requiert moins de RAM :

#+BEGIN_SRC python :results output
from sys import getsizeof
from typing import List, Tuple


def print_list_tuple_comparison(list_: List, tuple_: Tuple) -> None:
    list_size = getsizeof(list_)
    tuple_size = getsizeof(tuple_)
    diff = list_size - tuple_size
    print(f"Number of elements: {len(list_)}, list size: {list_size:<3}, tuple size: {tuple_size:<3}, diff: {diff} bytes ({diff/list_size*100:.2f}%)")


def print_list_tuple_ram_footprint(elements_nb: int) -> None:
    list_ = []
    tuple_ = ()

    print_list_tuple_comparison(list_, tuple_)

    for i in range(1, elements_nb + 1):
        list_.append(i)
        tuple_ = tuple(range(1, i + 1))
        
        print_list_tuple_comparison(list_, tuple_)


print_list_tuple_ram_footprint(10)
#+END_SRC
#+RESULTS:
: Number of elements: 0, list size: 56 , tuple size: 40 , diff: 16 bytes (28.57%)
: Number of elements: 1, list size: 88 , tuple size: 48 , diff: 40 bytes (45.45%)
: Number of elements: 2, list size: 88 , tuple size: 56 , diff: 32 bytes (36.36%)
: Number of elements: 3, list size: 88 , tuple size: 64 , diff: 24 bytes (27.27%)
: Number of elements: 4, list size: 88 , tuple size: 72 , diff: 16 bytes (18.18%)
: Number of elements: 5, list size: 120, tuple size: 80 , diff: 40 bytes (33.33%)
: Number of elements: 6, list size: 120, tuple size: 88 , diff: 32 bytes (26.67%)
: Number of elements: 7, list size: 120, tuple size: 96 , diff: 24 bytes (20.00%)
: Number of elements: 8, list size: 120, tuple size: 104, diff: 16 bytes (13.33%)
: Number of elements: 9, list size: 184, tuple size: 112, diff: 72 bytes (39.13%)
: Number of elements: 10, list size: 184, tuple size: 120, diff: 64 bytes (34.78%)

** Temps de création
Le /tuple/ est plus rapide à créé que la /list/:
#+BEGIN_SRC  python :results output
from timeit import timeit

tuple_elapsed_time = timeit("(1,2,3,4,5,6,7,8,9,10)", number=10_000_000)
list_elapsed_time = timeit("[1,2,3,4,5,6,7,8,9,10]", number=10_000_000)

print(f'Time needed to create a list  of 10 ints 10_000_000 times: {list_elapsed_time}')
print(f'Time needed to create a tuple of 10 ints 10_000_000 times: {tuple_elapsed_time} ({(list_elapsed_time - tuple_elapsed_time) / list_elapsed_time * 100:.2f}% faster)')
#+END_SRC

#+RESULTS:
: Time needed to create a list  of 10 ints 10_000_000 times: 0.6825288010004442
: Time needed to create a tuple of 10 ints 10_000_000 times: 0.0716032920172438 (89.51% faster)

*** Création d'une liste et accès à un de ses membres
#+BEGIN_SRC python :results output
from dis import dis

def my_list():
    x = [10, 20, 30, 'abc']
    y = x[0]

dis(my_list)
#+END_SRC

#+RESULTS:
:   4           0 LOAD_CONST               1 (10)
:               2 LOAD_CONST               2 (20)
:               4 LOAD_CONST               3 (30)
:               6 LOAD_CONST               4 ('abc')
:               8 BUILD_LIST               4
:              10 STORE_FAST               0 (x)
: 
:   5          12 LOAD_FAST                0 (x)
:              14 LOAD_CONST               5 (0)
:              16 BINARY_SUBSCR
:              18 STORE_FAST               1 (y)
:              20 LOAD_CONST               0 (None)
:              22 RETURN_VALUE

*** Création d'un tuple et accès à un de ses membres
#+BEGIN_SRC python :results output
from dis import dis

def my_tuple():
    x = (10, 20, 30, 'abc')
    y = x[0]

dis(my_tuple)
#+END_SRC
#+RESULTS:
:   4           0 LOAD_CONST               1 ((10, 20, 30, 'abc'))
:               2 STORE_FAST               0 (x)
: 
:   5           4 LOAD_FAST                0 (x)
:               6 LOAD_CONST               2 (0)
:               8 BINARY_SUBSCR
:              10 STORE_FAST               1 (y)
:              12 LOAD_CONST               0 (None)
:              14 RETURN_VALUE

La création d'un /tuple/ est plus rapide du fait de la [[id:26e1fdfb-1f8e-4c62-a08f-468a56ab03c8][Python peephole optimization]].

* Références
 * [[https://pub.towardsai.net/python-list-vs-tuple-an-in-depth-comparison-42c59348d8a8][Python List Vs. Tuple: An In-Depth Comparison - Medium]]
