How to get the number of Elements in a list in Python,The len() function can be used with a lot of types in Python - both built-in types and library types.
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.
>>> len([1,2,3])
3
>>> l = slist(range(10))
>>> l.length
10
>>> print l
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
items = []
items.append("apple")
items.append("orange")
items.append("banana")
print items.__len__()
Below is the code
items = [] items.append("apple") items.append("orange") items.append("banana") len(items) Output : 3
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.
OR
You can use below code also>>> len([1,2,3])
3
OR
>>> l = slist(range(10))
>>> l.length
10
>>> print l
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
OR
items = []
items.append("apple")
items.append("orange")
items.append("banana")
print items.__len__()
No comments:
Post a Comment