range() in una lista in Python
Spesso vogliamo creare un elenco contenente un valore continuo come, in un intervallo compreso tra 100 e 200. Parliamo di come creare un elenco utilizzando il file range()> funzione.
Funzionerà?
# Create a list in a range of 10-20> My_list> => [> range> (> 10> ,> 20> ,> 1> )]> > # Print the list> print> (My_list)> |
Produzione :
Come possiamo vedere nell'output, il risultato non è esattamente quello che ci aspettavamo perché Python non decomprime il risultato della funzione range().
Codice n. 1: Possiamo usare l'operatore di spacchettamento degli argomenti, ad es. * .
# Create a list in a range of 10-20> My_list> => [> *> range> (> 10> ,> 21> ,> 1> )]> > # Print the list> print> (My_list)> |
Produzione :
Come possiamo vedere nell'output, l'operatore di spacchettamento degli argomenti ha decompresso con successo il risultato della funzione range.
Codice n.2: Possiamo usare il extend()> funzione per decomprimere il risultato della funzione range.
# Create an empty list> My_list> => []> > # Value to begin and end with> start, end> => 10> ,> 20> > # Check if start value is smaller than end value> if> start # unpack the result My_list.extend(range(start, end)) # Append the last value My_list.append(end) # Print the list print(My_list)> |
Produzione :