Counting array elements in Python

PythonArrays

Python Problem Overview


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.

Python Solutions


Solution 1 - Python

The method len() returns the number of elements in the list.

Syntax:

len(myArray)

Eg:

myArray = [1, 2, 3]
len(myArray)

Output:

3

Solution 2 - Python

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.

Solution 3 - Python

If you have a multi-dimensional array, len() might not give you the value you are looking for. For instance:

import numpy as np
a = np.arange(10).reshape(2, 5)
print len(a) == 2

This code block will return true, telling you the size of the array is 2. However, there are in fact 10 elements in this 2D array. In the case of multi-dimensional arrays, len() gives you the length of the first dimension of the array i.e.

import numpy as np
len(a) == np.shape(a)[0]

To get the number of elements in a multi-dimensional array of arbitrary shape:

import numpy as np
size = 1
for dim in np.shape(a): size *= dim

Solution 4 - Python

Or,

myArray.__len__()

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

Solution 5 - Python

Before I saw this, I thought to myself, "I need to make a way to do this!"

for tempVar in arrayName: tempVar+=1

And then I thought, "There must be a simpler way to do this." and I was right.

len(arrayName)

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionUnkwnTechView Question on Stackoverflow
Solution 1 - PythonTrentView Answer on Stackoverflow
Solution 2 - PythonJeremy BrownView Answer on Stackoverflow
Solution 3 - Pythonuser2993689View Answer on Stackoverflow
Solution 4 - PythonKevin LittleView Answer on Stackoverflow
Solution 5 - PythonEvan YoungView Answer on Stackoverflow