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 matrizes em Phyton que é capaz de armazenar vários tipos de dados nele. Ele pode armazenar um número inteiro, flutuante, string, booleano 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 = ('Tecnologico', 'Cloudflare', 'Amazon')
print(string_list) # output -> ('Tecnologico', 'Cloudflare', 'Amazon')
boolean_list = (True, False)
print(boolean_list) # output -> (True, False)
nested_list = ((1, 2), (1.1, 2.2), ('Tecnologico', 'Cloudflare'), (True, False))
print(nested_list) # ((1, 2), (1.1, 2.2), ('Tecnologico', 'Cloudflare'), (True, False))
different_datatype_list = (1, 1.1, 'Tecnologico', True, (1, 1.1, 'Tecnologico', True))
print(different_datatype_list) # output -> (1, 1.1, 'Tecnologico', True, (1, 1.1, 'Tecnologico', True))
listas Python pode ser criado usando um colchete ou uma função de construtor de lista.
square_bracket_list = (1, 1.1, 'Tecnologico', True, (1, 1.1, 'Tecnologico', True))
print(square_bracket_list) # output -> (1, 1.1, 'Tecnologico', True, (1, 1.1, 'Tecnologico', True))
constructor_list = list((1, 1.1, 'Tecnologico', True, (1, 1.1, 'Tecnologico', True)))
print(constructor_list) # output -> (1, 1.1, 'Tecnologico', True, (1, 1.1, 'Tecnologico', True))
O de cima lista_de_colchetes_quadrados é uma lista criada usando quadrado suporte(()), lista_de_construtores é uma lista criada usando o construtor de lista. Ambos produzem apenas a mesma saída de lista.
A lista pode ser alterada, permitir duplicatas nela e ser acessível usando um índice.
Métodos para encontrar o comprimento da lista
- função embutida len()
- método length_hint do operador
- função personalizada e contador
Método 1: função embutida len()
O len () é uma função embutida do python usada para encontrar o comprimento da lista e também para outros iteráveis como Set, Tuples, Dictionary.
Trecho de exemplo
languages = ('Python', 'Java', 'C++', 'PHP', 'nodeJS')
languages_length = len(languages)
print('Length of the Language List is: ',languages_length)
Saída
Length of the Language List is: 5
Espero que você tenha o Python instalado, se não, 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.
Trecho 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)
Saída
Length of the Language List using Operator is: 5
Método 3: função personalizada e contador
Neste método para encontrar o comprimento da Lista, vamos usar o método tradicional usando for-loop e counter.
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.
Trecho de função personalizada
def iterable_count(iterable):
length = 0
for item in iterable:
length+=1
return length
Trecho 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)
Saída
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)
Saída
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.
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)
Saída
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 estiverem 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.