Python | Maneras de encontrar la longitud de la lista

La lista, que es una parte integral de la programación diaria de Python, debe ser aprendida por todos los usuarios de Python y tener un conocimiento de su utilidad y operaciones es esencial y siempre una ventaja. Entonces, este artículo analiza una de esas utilidades para encontrar el no. de elementos en una lista.
 

Método 1: método ingenuo

En este método, uno simplemente ejecuta un ciclo y aumenta el contador hasta el último elemento de la lista para conocer su conteo. Esta es la estrategia más básica que puede emplearse posiblemente en ausencia de otras técnicas actuales.
Código n.º 1: demostración de cómo encontrar la longitud de una lista usando el método Naive

Python3

# Python code to demonstrate
# length of list
# using naive method
 
# Initializing list
test_list = [ 1, 4, 5, 7, 8 ]
 
# Printing test_list
print ("The list is : " + str(test_list))
 
# Finding length of list
# using loop
# Initializing counter
counter = 0
for i in test_list:
     
    # incrementing counter
    counter = counter + 1
 
# Printing length of list
print ("Length of list using naive method is : " + str(counter))

Producción : 

The list is : [1, 4, 5, 7, 8]
Length of list using naive method is : 5

Método 2: Usar len()

El método len() ofrece la forma más utilizada y fácil de encontrar la longitud de cualquier lista. Esta es la técnica más convencional adoptada por todos los programadores en la actualidad.

Python3

# Python program to demonstrate working
# of len()
a = []
a.append("Hello")
a.append("Geeks")
a.append("For")
a.append("Geeks")
print("The length of list is: ", len(a))
Producción: 

The length of list is:  4

 

Python3

# Python program to demonstrate working
# of len()
n = len([10, 20, 30])
print("The length of list is: ", n)
Producción: 

The length of list is:  3

 

Método 3: Usar length_hint()

Esta técnica es una técnica menos conocida para encontrar la longitud de la lista. Este método en particular se define en la clase de operador y también puede indicar el no. de elementos presentes en la lista. 
Código n.º 2: demostración de cómo encontrar la longitud de la lista usando len() y length_hint() 

Python3

# Python code to demonstrate
# length of list
# using len() and length_hint
from operator import length_hint
 
# Initializing list
test_list = [ 1, 4, 5, 7, 8 ]
 
# Printing test_list
print ("The list is : " + str(test_list))
 
# Finding length of list
# using len()
list_len = len(test_list)
 
# Finding length of list
# using length_hint()
list_len_hint = length_hint(test_list)
 
# Printing length of list
print ("Length of list using len() is : " + str(list_len))
print ("Length of list using length_hint() is : " + str(list_len_hint))

Producción : 

The list is : [1, 4, 5, 7, 8]
Length of list using len() is : 5
Length of list using length_hint() is : 5

Análisis de rendimiento: ingenuo frente a len() frente a length_hint()

A la hora de elegir entre alternativas siempre es necesario tener un motivo válido para elegir una sobre otra. Esta sección hace un análisis de tiempo de cuánto tiempo lleva ejecutarlos todos para ofrecer una mejor opción de uso.
Código #3: Análisis de desempeño 

Python3

# Python code to demonstrate
# length of list
# Performance Analysis
from operator import length_hint
import time
 
# Initializing list
test_list = [ 1, 4, 5, 7, 8 ]
 
# Printing test_list
print ("The list is : " + str(test_list))
 
# Finding length of list
# using loop
# Initializing counter
start_time_naive = time.time()
counter = 0
for i in test_list:
     
    # incrementing counter
    counter = counter + 1
end_time_naive = str(time.time() - start_time_naive)
 
# Finding length of list
# using len()
start_time_len = time.time()
list_len = len(test_list)
end_time_len = str(time.time() - start_time_len)
 
# Finding length of list
# using length_hint()
start_time_hint = time.time()
list_len_hint = length_hint(test_list)
end_time_hint = str(time.time() - start_time_hint)
 
# Printing Times of each
print ("Time taken using naive method is : " + end_time_naive)
print ("Time taken using len() is : " + end_time_len)
print ("Time taken using length_hint() is : " + end_time_hint)

Producción : 

The list is : [1, 4, 5, 7, 8]
Time taken using naive method is : 2.6226043701171875e-06
Time taken using len() is : 1.1920928955078125e-06
Time taken using length_hint() is : 1.430511474609375e-06

Conclusión: 

En las imágenes a continuación, se puede ver claramente que el tiempo empleado es ingenuo >> length_hint() > len() , pero el tiempo empleado depende en gran medida del sistema operativo y de varios de sus parámetros. En dos ejecuciones consecutivas, puede obtener resultados contrastantes, de hecho, a veces, ingenuo toma el menor tiempo de tres. Todas las 6 permutaciones posibles son posibles.

  ingenuo > len() > length_hint()

ingenuo > len()=longitud_pista() 

ingenuo > length_hint() >len() 

ingenuo > length_hint() > len()

Publicación traducida automáticamente

Artículo escrito por manjeet_04 y traducido por Barcelona Geeks. The original can be accessed here. Licence: CCBY-SA

Deja una respuesta

Tu dirección de correo electrónico no será publicada. Los campos obligatorios están marcados con *