In Desarrollo Última actualización:
Comparte en:
Cloudways ofrece alojamiento en la nube administrado para empresas de cualquier tamaño para alojar un sitio web o aplicaciones web complejas.

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.

¿Qué es la lista de Python?

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 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.

Métodos para encontrar la longitud de la lista

  • función incorporada len()
  • método length_hint del operador
  • función personalizada y contador

Método 1: función incorporada len()

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.

Método 2: método length_hint del operador

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

Método 3: función personalizada y contador

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

Analizando esos 3 métodos

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.

Para Concluir

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.

Comparte en:
  • Baskar de Aghilan
    Autor
    Ingeniero Informático de profesión. Le encanta compartir y ayudar cosas con los demás. Le encanta escribir artículos para ayudar a la comunidad.

Gracias a nuestros patrocinadores

Más lecturas interesantes sobre el desarrollo

Impulse su negocio

Algunas de las herramientas y servicios para ayudar a que su negocio crezca.
  • La herramienta de conversión de texto a voz que utiliza IA para generar voces realistas parecidas a las humanas.

    Prueba la IA de Murf
  • Web scraping, proxy residencial, administrador de proxy, desbloqueador web, rastreador de motores de búsqueda y todo lo que necesita para recopilar datos web.

    Prueba Brightdata
  • Monday.com es un sistema operativo de trabajo todo en uno para ayudarlo a administrar proyectos, tareas, trabajo, ventas, CRM, operaciones, workflows, y más.

    Intente Monday
  • Intruder es un escáner de vulnerabilidades en línea que encuentra debilidades de ciberseguridad en su infraestructura, para evitar costosas filtraciones de datos.

    Intente Intruder