En este artículo, vemos cómo verificar la longitud de una lista en algunos de los sencillos pasos y analizar cuál es mejor.
What is Python List?
La lista es una colección de matrices en Python que es capaz de almacenar múltiples tipos de datos en él. Puede almacenar un número entero, flotante, cadena, booleano o incluso una lista dentro de una lista.
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]]
Listas de Python se puede crear utilizando un cuadrado corchete o una función constructora de listas.
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, 'Geekflare', True, [1, 1.1, 'Geekflare', True]))
print(constructor_list) # output -> [1, 1.1, 'Geekflare', True, [1, 1.1, 'Geekflare', True]]
Lo anterior lista_de_corchetes es una lista creada usando corchetes ([]), lista_constructor es una lista creada usando el constructor de listas. Ambos producen la misma salida de lista solamente.
La lista puede modificarse, permitir duplicados y ser accesible mediante un índice.
Methods to find List Length
- función incorporada len()
- método length_hint del operador
- función personalizada y contador
Method 1: len() inbuilt function
El len() es una función incorporada de Python que se usa para encontrar la longitud de la lista y también para otros iterables como Set, Tuples, Dictionary.
Fragmento de ejemplo
languages = ['Python', 'Java', 'C++', 'PHP', 'nodeJS']
languages_length = len(languages)
print('Length of the Language List is: ',languages_length)
Salida
Length of the Language List is: 5
Espero que tengas Python instalado, si no, puedes usar un compilador de Python en línea para practicar el código.
Method 2: length_hint method from operator
longitud_sugerencia se utiliza para devolver la longitud de un objeto iterable (como Lista, Conjunto, Tuplas, Diccionario). Está disponible dentro del módulo de operador de python. No disponible como otros operadores incorporados.
Fragmento de ejemplo
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)
Salida
Length of the Language List using Operator is: 5
Method 3: Custom function & counter
En este método para encontrar la longitud de la Lista, vamos a usar el método tradicional usando for-loop y counter.
Para eso, vamos a escribir una función en python. que toma una lista u otro iterable como argumento y devuelve la longitud de un iterable.
Fragmento de función personalizada
def iterable_count(iterable):
length = 0
for item in iterable:
length+=1
return length
Fragmento de ejemplo
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)
Salida
Length of the Language List using Custom function is: 5
Analysing those 3 methods
Análisis de rendimiento para una lista grande
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)
Salida
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
Como podemos ver longitud_sugerencia is más rápido(3.0621886253356934e-06) cuando los datos están en millones. Esto se debe a que el tiempo de ejecución de CPython utiliza sugerencias de longitud. Donde se llama envoltura de python.
Análisis de rendimiento para una lista pequeña
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)
Salida
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
Como podemos ver len () is más rápido(7.813796401023865e-07) cuando los datos están en miles o menos.
En ambos casos, nuestra función personalizada con contador lleva más tiempo que ambos métodos.
Conclusion
En este artículo, comprendemos diferentes formas de verificar la longitud de la lista y cómo verifican rápidamente la longitud de la lista.