python - Comment obtenir le nombre d'éléments dans une liste

Mots clés : pythonlistpython

meilleur 5 Réponses python - Comment obtenir le nombre d'éléments dans une liste

vote vote

91

>>> len([1, 2, 3]) 3 
vote vote

86

items = [] items.append("apple") items.append("orange") items.append("banana") 
len(items) 
items.__len__() 
>>> all(hasattr(cls, '__len__') for cls in (str, bytes, tuple, list,                                              range, dict, set, frozenset)) True 
if len(items) == required_length:     ... 
if len(items):      ... 
if items:     # Then we have some items, not empty!     ... 
if not items: # Then we have an empty list!     ... 
vote vote

71

class slist(list):     @property     def length(self):         return len(self) 
>>> l = slist(range(10)) >>> l.length 10 >>> print l [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] 
vote vote

64

>>> from operator import length_hint >>> l = ["apple", "orange", "banana"] >>> len(l) 3 >>> length_hint(l) 3  >>> list_iterator = iter(l) >>> len(list_iterator) TypeError: object of type 'list_iterator' has no len() >>> length_hint(list_iterator) 3 
vote vote

54

def count(list):     item_count = 0     for item in list[:]:         item_count += 1     return item_count  count([1,2,3,4,5]) 
class MyList(object):     def __init__(self):         self._data = []         self.length = 0 # length tracker that takes up memory but makes length op O(1) time                   # the implicit iterator in a list class     def __iter__(self):         for elem in self._data:             yield elem                  def add(self, elem):         self._data.append(elem)         self.length += 1                  def remove(self, elem):         self._data.remove(elem)         self.length -= 1              mylist = MyList() mylist.add(1) mylist.add(2) mylist.add(3) print(mylist.length) # 3 mylist.remove(3) print(mylist.length) # 2 

Questions similaires