收录日期:2019/10/18 22:12:53 时间:2014-10-08 11:21:36 标签:python,list
items = []
items.append("apple")
items.append("orange")
items.append("banana")

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

How do I do it right?

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

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.

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

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__() 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.

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

Answering your question as the examples also givven above:

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

print items.__len__()

If you need to know MEMORY USAGE of a given type, you can use the function sys.getsizeof

>>> from sys import getsizeof
>>> l = []
>>> getsizeof(l)
64
>>> l.append(10)
>>> getsizeof(l)
96
>>> getsizeof(10)
28
>>> l.append(True)
>>> getsizeof(l)
96
>>> getsizeof(True)
28
>>> getsizeof("toto")
53
>>> getsizeof(10.5)
24

This function works fine for native python types https://docs.python.org/dev/library/sys.html#sys.getsizeof

But if you need to analyse complex structures, have a look at this recipe.

The simplest way

>>> list = [2,7,4,6,9,8,5,4]
>>> length = len(list)
>>> length
8

Python len() function is enough for determining list size. There is also __len__() function you can use.

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

print len(items) #it will print  3
print items.__len__()   #it will print 3