Sprawdź długość listy w Pythonie w 3 prostych krokach

W tym artykule zobaczymy, jak sprawdzić długość listy w niektórych prostych krokach i przeanalizować, która z nich jest lepsza.

Co to jest lista Pythona?

Lista jest zbiorem tablic w Pythonie, który może przechowywać w niej wiele typów danych. Może przechowywać liczbę całkowitą, zmiennoprzecinkową, łańcuchową, logiczną, a nawet listę wewnątrz listy.

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

Listy w Pythonie można tworzyć za pomocą nawiasów kwadratowych lub funkcji konstruktora listy.

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

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

Powyższa lista nawiasów kwadratowych jest listą utworzoną za pomocą nawiasu kwadratowego ([]), konstruktor_list to lista utworzona za pomocą konstruktora listy. Oba generują tylko te same dane wyjściowe listy.

Lista może być zmienna, dopuszczać duplikaty w niej i być dostępna za pomocą indeksu.

Metody znajdowania długości listy

  • len() wbudowana funkcja
  • metoda length_hint od operatora
  • funkcja niestandardowa i licznik

Metoda 1: wbudowana funkcja len()

len() jest wbudowaną funkcją Pythona, używaną do znajdowania długości listy, a także dla innych iterowalnych, takich jak Set, Tuples, Dictionary.

Przykładowy fragment

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

languages_length = len(languages)

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

Wyjście

Length of the Language List is:  5

Mam nadzieję, że masz zainstalowany Python, jeśli nie, możesz użyć kompilatora Pythona online, aby przećwiczyć kod.

Metoda 2: metoda length_hint od operatora

length_hint służy do zwracania długości obiektu iterowalnego (takiego jak List, Set, Tuples, Dictionary). Jest dostępny w module operatora Pythona. Niedostępne jak inne wbudowane operatory.

Przykładowy fragment

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)

Wyjście

Length of the Language List using Operator is:  5

Metoda 3: Niestandardowa funkcja i licznik

W tej metodzie, aby znaleźć długość listy, użyjemy tradycyjnej metody, używając pętli for i licznika.

W tym celu napiszemy funkcję w Pythonie. który przyjmuje listę lub inną iterowaną jako argument i zwraca długość iterowalnego.

Fragment funkcji niestandardowej

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

Przykładowy fragment

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)

Wyjście

Length of the Language List using Custom function is:  5

Analizując te 3 metody

Analiza wydajności dla dużej listy

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)

Wyjście

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

Jak widać length_hint jest szybsze (3.0621886253356934e-06), gdy dane są w milionach. Dzieje się tak, ponieważ wskazówki dotyczące długości są używane przez środowisko uruchomieniowe CPython. Gdzie nazywa się to opakowaniem Pythona.

Analiza wydajności dla małej listy

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)

Wyjście

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

Jak widzimy, len() jest szybsze (7,813796401023865e-07), gdy dane są w tysiącach lub mniej.

W obu przypadkach nasza niestandardowa funkcja z licznikiem zajmuje więcej czasu niż obie metody.

Wniosek

W tym artykule rozumiemy różne sposoby sprawdzania długości listy i jak szybko sprawdzają długość listy.