Controlla la lunghezza dell’elenco in Python in 3 semplici passaggi

In questo articolo, vediamo come controllare la lunghezza di un elenco in alcuni dei semplici passaggi e analizzare quale è il migliore.

Cos’è Python List?

L’elenco è una raccolta di array in Python che è in grado di memorizzare più tipi di dati al suo interno. Può memorizzare un numero intero, float, stringa, booleano o persino un elenco all’interno di un elenco.

int_list = [1, 2, 3, 4, 5]

print(int_list) # output -> [1, 2, 3, 4, 5]

float_list = [1.1, 2.2, 3.3, 4.4, 5.5]

print(float_list) # output -> [1.1, 2.2, 3.3, 4.4, 5.5]

string_list = ['Geekflare', 'Cloudflare', 'Amazon']

print(string_list) # output -> ['Geekflare', 'Cloudflare', 'Amazon']

boolean_list = [True, False]

print(boolean_list) # output -> [True, False]

nested_list = [[1, 2], [1.1, 2.2], ['Geekflare', 'Cloudflare'], [True, False]]

print(nested_list) # [[1, 2], [1.1, 2.2], ['Geekflare', 'Cloudflare'], [True, False]]

different_datatype_list = [1, 1.1, 'Geekflare', True, [1, 1.1, 'Geekflare', True]]

print(different_datatype_list) # output -> [1, 1.1, 'Geekflare', True, [1, 1.1, 'Geekflare', True]]

Gli elenchi Python possono essere creati utilizzando una parentesi quadra o una funzione di costruzione di elenchi.

square_bracket_list = [1, 1.1, 'Geekflare', True, [1, 1.1, 'Geekflare', True]]

print(square_bracket_list) # output -> [1, 1.1, 'Geekflare', True, [1, 1.1, 'Geekflare', True]]

constructor_list = list((1, 1.1, 'winadmin.it', True, [1, 1.1, 'Geekflare', True]))

print(constructor_list) # output -> [1, 1.1, 'Geekflare', True, [1, 1.1, 'Geekflare', True]]

L’elenco di parentesi quadre sopra è un elenco creato utilizzando parentesi quadre([]), constructor_list è un elenco creato utilizzando il costruttore di elenchi. Entrambi producono solo lo stesso output dell’elenco.

L’elenco può essere modificabile, consentire duplicati ed essere accessibile utilizzando un indice.

Metodi per trovare la lunghezza dell’elenco

  • len() funzione integrata
  • length_hint metodo dall’operatore
  • funzione e contatore personalizzati

Metodo 1: funzione integrata len()

len() è una funzione integrata in Python utilizzata per trovare la lunghezza dell’elenco e anche per altri iterables come Set, Tuples, Dictionary.

Esempio di frammento

languages = ['Python', 'Java', 'C++', 'PHP', 'nodeJS']

languages_length = len(languages)

print('Length of the Language List is: ',languages_length)

Produzione

Length of the Language List is:  5

Spero che tu abbia installato Python, in caso contrario puoi usare un compilatore Python online per esercitarti con il codice.

Metodo 2: metodo length_hint dall’operatore

length_hint viene utilizzato per restituire la lunghezza di un oggetto iterabile (come List, Set, Tuples, Dictionary). È disponibile all’interno del modulo operatore Python. Non disponibile come altri operatori integrati.

Esempio di frammento

import operator

languages = ['Python', 'Java', 'C++', 'PHP', 'nodeJS']

languages_length = operator.length_hint(languages)

print('Length of the Language List using Operator is: ',languages_length)

Produzione

Length of the Language List using Operator is:  5

Metodo 3: funzione e contatore personalizzati

In questo metodo per trovare la lunghezza della List, useremo il metodo tradizionale usando for-loop e counter.

Per questo, scriveremo una funzione in Python. che accetta una lista o un altro iterabile come argomento e restituisce la lunghezza di un iterabile.

Frammento di funzione personalizzata

def iterable_count(iterable):
  length = 0
  for item in iterable:
    length+=1
  return length

Esempio di frammento

def iterable_count(iterable):
  length = 0
  for item in iterable:
    length+=1
  return length

languages = ['Python', 'Java', 'C++', 'PHP', 'nodeJS']

languages_length = iterable_count(languages)

print('Length of the Language List using Custom function is: ',languages_length)

Produzione

Length of the Language List using Custom function is:  5

Analizzando questi 3 metodi

Analisi delle prestazioni per un ampio elenco

import timeit # for benchmarking & profiling
import operator

def iterable_count(iterable):
  length = 0
  for item in iterable:
    length+=1
  return length

integer_list = list(range(1, 9999999))

#length check using len()
start_time = timeit.default_timer()
len_length = len(integer_list)
print(timeit.default_timer() - start_time, 'Length of the Integer List using len() is: ',len_length)

#length check using operator.length_hint
start_time = timeit.default_timer()
len_length = operator.length_hint(integer_list)
print(timeit.default_timer() - start_time, 'Length of the Integer List using length_hint is: ',len_length)

start_time = timeit.default_timer()
iterable_count_length = iterable_count(integer_list)
print(timeit.default_timer() - start_time, 'Length of the Integer List using Custom function is: ',iterable_count_length)

Produzione

3.957189619541168e-06 Length of the Integer List using len() is:  9999998
3.0621886253356934e-06 Length of the Integer List using length_hint is:  9999998
0.4059128537774086 Length of the Integer List using Custom function is:  9999998

Come possiamo vedere, length_hint è più veloce (3.0621886253356934e-06) quando i dati sono in milioni. È perché i suggerimenti sulla lunghezza vengono utilizzati dal runtime di CPython. Dove si chiama wrapper python.

Analisi delle prestazioni per un piccolo elenco

import timeit # for benchmarking & profiling
import operator

def iterable_count(iterable):
  length = 0
  for item in iterable:
    length+=1
  return length

integer_list = list(range(1, 100))

#length check using len()
start_time = timeit.default_timer()
len_length = len(integer_list)
print(timeit.default_timer() - start_time, 'Length of the Integer List using len() is: ',len_length)

#length check using operator.length_hint
start_time = timeit.default_timer()
len_length = operator.length_hint(integer_list)
print(timeit.default_timer() - start_time, 'Length of the Integer List using length_hint is: ',len_length)

start_time = timeit.default_timer()
iterable_count_length = iterable_count(integer_list)
print(timeit.default_timer() - start_time, 'Length of the Integer List using Custom function is: ',iterable_count_length)

Produzione

7.813796401023865e-07 Length of the Integer List using len() is:  99
1.1278316378593445e-06 Length of the Integer List using length_hint is:  99
3.462657332420349e-06 Length of the Integer List using Custom function is:  99

Come possiamo vedere len() è più veloce(7.813796401023865e-07) quando i dati sono in migliaia o meno.

In entrambi i casi, la nostra funzione personalizzata con contatore richiede più tempo di entrambi i metodi.

Conclusione

In questo articolo, comprendiamo diversi modi per controllare la lunghezza dell’elenco e come controllano rapidamente la lunghezza dell’elenco.