Gli oggetti di tipo range, intervalli, si utilizzano nei cicli for
1 2 3 |
for i in range(...): ... ... |
Osserva
- Un intervallo rappresenta una sequenza immutabile di numeri interi
- Gli intervalli implementano le operazioni sulle sequenze comuni tranne concatenazione e ripetizione
- Un intervallo memorizza START, STOP e STEP e calcola i singoli elementi o intervalli al volo (non occupa memoria superflua)
Costruttori
range(STOP) | [0, 1, …, STOP) |
range(START, STOP) | [START, START+1, …, STOP) |
range(START, STOP, STEP) | [START, START+STEP, START+2*STEP, …, STOP) r[i]=START + i*STEP START <= r[i] < STOP |
range(START, STOP, -STEP) | [START, START-STEP, START-2*STEP, …, STOP) r[i]=START – i*STEP START >= r[i] > STOP |
Osserva
- START, STOP, STEP devono essere interi
- Se STEP = 0 si ottiene un errore
- Se STOP <= START e il passo è positivo si ottiene un intervallo vuoto
- Le costanti START, STOP, STEP si utilizzano anche nello SLICING
Operatori
r1 == r2 | Gli intervalli sono uguali? Le sequenze effettive… |
r1 != r2 | Gli intervalli sono diversi? Le sequenze effettive… |
x in r1 | x appartiene a r1? |
x not in r1 | x NON appartiene a r1? |
r1[p] | L’elemento alla posizione p |
r1[n1 : n2 : n3] | Restituisce un range (costruito tramite SLICING) |
Funzioni / metodi
r1.count(x) | Restituisce il numero di occorrenze di x |
r1.index(x) | Restituisce la posizione della prima occorrenza di x |
len(r1) | Restituisce il numero di elementi |
max(r1) | Restituisce il valore massimo |
min(r1) | Restituisce il valore minimo |
sum(r1) | Restituisce la somma degli elementi |
... | … |
Prova
1 2 3 4 5 6 7 8 9 10 11 |
# Da 0 a STOP-1 range(10) # 0 1 2 3 4 5 6 7 8 9 range(0) # # Da START a STOP-1 range(5,10) # 5 6 7 8 9 range(-5,5) # -5 -4 -3 -2 -1 0 1 2 3 4 range(10,5) # # Da START a STOP-1 con passo positivo range(5,10,2) # 5 7 9 # Da START a STOP+1 con passo negativo range(10,5,-1) # 10 9 8 7 6 |
Un oggetto di tipo range() permette molte manipolazioni inaspettate…
1 2 3 4 5 6 7 8 9 10 11 12 13 |
r=range(100,150) # range(100,150) r==range(100,150,1) # True r==range(100,150,2) # False len(r) # 50 min(r) # 100 max(r) # 149 sum(r) # 6225 10 in r # False 10 not in r # True r[0] # 100 r[10:20] # range(110,120) r.index(149) # 49 r.count(149) # 1 |