How to get the number of elements in a list in Pyt

2019-01-01 16:40发布

items = []
items.append("apple")
items.append("orange")
items.append("banana")

# FAKE METHOD::
items.amount()  # Should return 3

How do I get the number of elements in the list?

标签: python list
6条回答
皆成旧梦
2楼-- · 2019-01-01 16:57

Answering your question as the examples also given previously:

items = []
items.append("apple")
items.append("orange")
items.append("banana")

print items.__len__()
查看更多
情到深处是孤独
3楼-- · 2019-01-01 16:58

The len() function can be used with a lot of types in Python - both built-in types and library types.

>>> len([1,2,3])
3
查看更多
浮光初槿花落
4楼-- · 2019-01-01 17:04

How to get the size of a list?

To find the size of a list, use the builtin function, len:

items = []
items.append("apple")
items.append("orange")
items.append("banana")

And now:

len(items)

returns 3.

Explanation

Everything in Python is an object, including lists. All objects have a header of some sort in the C implementation.

Lists and other similar builtin objects with a "size" in Python, in particular, have an attribute called ob_size, where the number of elements in the object is cached. So checking the number of objects in a list is very fast.

But if you're checking if list size is zero or not, don't use len - instead, put the list in a boolean context - it treated as False if empty, True otherwise.

From the docs

len(s)

Return the length (the number of items) of an object. The argument may be a sequence (such as a string, bytes, tuple, list, or range) or a collection (such as a dictionary, set, or frozen set).

len is implemented with __len__, from the data model docs:

object.__len__(self)

Called to implement the built-in function len(). Should return the length of the object, an integer >= 0. Also, an object that doesn’t define a __nonzero__() [in Python 2 or __bool__() in Python 3] method and whose __len__() method returns zero is considered to be false in a Boolean context.

And we can also see that __len__ is a method of lists:

items.__len__()

returns 3.

Builtin types you can get the len (length) of

And in fact we see we can get this information for all of the described types:

>>> all(hasattr(cls, '__len__') for cls in (str, bytes, tuple, list, 
                                            xrange, dict, set, frozenset))
True

Do not use len to test for an empty or nonempty list

To test for a specific length, of course, simply test for equality:

if len(items) == required_length:
    ...

But there's a special case for testing for a zero length list or the inverse. In that case, do not test for equality.

Also, do not do:

if len(items): 
    ...

Instead, simply do:

if items:     # Then we have some items, not empty!
    ...

or

if not items: # Then we have an empty list!
    ...

I explain why here but in short, if items or if not items is both more readable and more performant.

查看更多
路过你的时光
5楼-- · 2019-01-01 17:16

Besides len you can also use operator.length_hint (requires python 3.4+). For normal list both are equivalent but length_hint makes it possible to get the length of a list-iterator, which could be useful in certain circumstances:

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

But length_hint is by definition only a "hint", so most of the time len is better.

I've seen several answers suggesting accessing __len__. This is alright when dealing with built-in classes like list but it could lead to problems with custom classes because len (and length_hint) implement some safety checks. For example both do not allow negative lengths or lengths that exceed a certain value (the sys.maxsize value). So it's always safer to use the len function instead of the __len__ method!

查看更多
大哥的爱人
6楼-- · 2019-01-01 17:17

And for completeness (taking one for the team with the downvotes), it is possible without using the len() function (I would not condone this as a good option):

def count(list):
  item_count = 0
  for item in list[:]:
    item_count = item_count + 1
  return item_count

count([1,2,3,4,5])

(the colon in list[:] is implicit, therefore also optional)

查看更多
荒废的爱情
7楼-- · 2019-01-01 17:18

While this may not be useful due to the fact that it'd make a lot more sense as being "out of the box" functionality, a fairly simple hack would be to build a class with a length property:

class slist(list):
    @property
    def length(self):
        return len(self)

You can use it like so:

>>> l = slist(range(10))
>>> l.length
10
>>> print l
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

Essentially, it's exactly identical to a list object, with the added benefit of having an OOP-friendly length property.

As always, your mileage may vary.

查看更多
登录 后发表回答