tags:

views:

9902

answers:

3

How can I count the number of elements in an array, because contrary to logic array.count(string) does not count all the elements in the array, it just searches for the number of occurrences of string.

+26  A: 

len(myArray)

Trent
A: 

Or,

myArray.__len__()

if you want to be oopy; "len(myArray)" is a lot easier to type! :)

Kevin Little
Race conditions! Yuck.
Gregg Lind
Thats a definite Yuk.
Unkwntech
@Gregg Lind, This does not introduce a race condition. (It is, however, as yucky as it gets.)
Mike Graham
The race condition was between me and another poster! Note my *even more downvoted answer* below!
Gregg Lind
(I realize now, that my answer is deleted, but essentially Kevin Little and I said exactly the same thing at the same time).
Gregg Lind
+5  A: 

len is a built-in function that calls the given container object's __len__ member function to get the number of elements in the object.

Functions encased with double underscores are usually "special methods" implementing one of the standard interfaces in Python (container, number, etc). Special methods are used via syntactic sugar (object creation, container indexing and slicing, attribute access, built-in functions, etc.).

Using obj.__len__() wouldn't be the correct way of using the special method, but I don't see why the others were modded down so much.

Jeremy Brown
Especially when both of us mentioned that is was bad form. Understanding what length "really" does is important in it's own right.
Gregg Lind