我们有多种方法获取list中元素的数量
# Python len()
list1 = [1, 2, 3]
n = len(list1)
print("The length of list using len() is: ", n)
# using for loop
list2 = [1, 2, 3, 4, 5]
counter = 0
for i in list2:
# incrementing counter
counter = counter + 1
print("Length of list using for loop is : " + str(counter))
# using length_hint
from operator import length_hint
# Initializing list
list3 = [1, 4, 5, 7, 8]
# Finding length of list
# using length_hint()
list_len_hint = length_hint(list3)
print("Length of list using length_hint() is : " + str(list_len_hint))
# using sum()
# Initializing list
list4 = [1, 2, 3, 4, 5, 6]
# Finding length of list
# using sum()
list_len_sum = sum(1 for i in list4)
print("Length of list using sum() is : " + str(list_len_sum))
# using a list comprehension
list5 = [1, 4, 5, 7, 8]
list_len_comp = sum(1 for _ in list5)
print("Length of list using list comprehension is : " + str(list_len_comp))
# Define a function to count the number of elements in a list using recursion
def count_elements_recursion(lst):
# Base case: if the list is empty, return 0
if not lst:
return 0
# Recursive case: add 1 to the count of the remaining elements in the list
return 1 + count_elements_recursion(lst[1:])
# Test the function with a sample list
list6 = [1, 2, 3, 4, 5, 6, 7, 8]
print("The length of the list is: " + str(count_elements_recursion(list6)))
# using enumerate function
list7 = [1, 4, 5, 7, 8]
l = 0
for i, a in enumerate(list7):
l += 1
print(l)
from collections import Counter
# Initializing list
list8 = [1, 2, 3, 4, 5, 6, 7, 8, 9]
# Finding length of list using Counter()
list_len = sum(Counter(list8).values())
print("Length of list using Counter() is: " + str(list_len))