Verifique o comprimento da lista em Python em 3 etapas fáceis

Neste artigo, veremos como verificar o comprimento de uma lista em algumas das etapas fáceis e analisar qual é o melhor.

O que é Lista Python?

A lista é uma coleção de arrays em Python que é capaz de armazenar vários tipos de dados nela. Ele pode armazenar um inteiro, float, string, boolean ou até mesmo uma lista dentro de uma 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]]

As listas Python podem ser criadas usando um colchete ou uma função construtora de lista.

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, 'etechpt.com', True, [1, 1.1, 'Geekflare', True]))

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

A lista de colchetes acima é uma lista criada usando colchetes ([]), constructor_list é uma lista criada usando o construtor de lista. Ambos produzem apenas a mesma saída de lista.

  Como mover uma janela fora da tela para a tela principal

A lista pode ser alterada, permitir duplicatas nela e ser acessível usando um índice.

Métodos para encontrar o comprimento da lista

  • len() função embutida
  • método length_hint do operador
  • função personalizada e contador

Método 1: função embutida len()

O len() é uma função embutida em python usada para encontrar o comprimento da lista e também para outros iteráveis ​​como Set, Tuples, Dictionary.

Fragmento de Exemplo

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

languages_length = len(languages)

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

Resultado

Length of the Language List is:  5

Espero que você tenha o Python instalado, caso contrário, você pode usar um compilador Python online para praticar o código.

Método 2: método length_hint do operador

length_hint é usado para retornar um comprimento de um objeto iterável (como List, Set, Tuples, Dictionary). Ele está disponível dentro do módulo do operador python. Não disponível como outros operadores embutidos.

  Como fazer uma curva de calibração linear no Excel

Fragmento de Exemplo

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)

Resultado

Length of the Language List using Operator is:  5

Método 3: Função e contador personalizados

Neste método para encontrar o comprimento da Lista, usaremos o método tradicional usando loop for e contador.

Para isso, vamos escrever uma função em python. que recebe uma lista ou outro iterável como argumento e retorna o comprimento de um iterável.

Fragmento de função personalizada

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

Fragmento de Exemplo

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)

Resultado

Length of the Language List using Custom function is:  5

Analisando esses 3 métodos

Análise de desempenho para uma 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)

Resultado

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, length_hint é mais rápido (3.0621886253356934e-06) quando os dados estão em milhões. É porque as dicas de comprimento são usadas pelo tempo de execução do CPython. Onde é chamado de wrapper python.

  O que fazer se meu Mac continuar reiniciando? 10 dicas para corrigir o problema

Análise de desempenho para uma pequena lista

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)

Resultado

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() é mais rápido (7.813796401023865e-07) quando os dados estão em milhares ou menos.

Em ambos os casos, nossa função personalizada com contador leva mais tempo do que os dois métodos.

Conclusão

Neste artigo, entendemos diferentes maneiras de verificar o tamanho da lista e como eles verificam rapidamente o tamanho da lista.