# Counting array elements in Python [duplicate]

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.

Asked by:

**Melissa161**| Posted: 28-01-2022

# Answer 1

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

Syntax:

```
len(myArray)
```

Eg:

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

Output:

```
3
```

Answered by: **Aston751**| Posted: 01-03-2022

# Answer 2

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

**Joyce856**| Posted: 01-03-2022

# Answer 3

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

Answered by: **Walter352**| Posted: 01-03-2022

# Answer 4

Or,

```
myArray.__len__()
```

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

Answered by:**Lenny947**| Posted: 01-03-2022

# Answer 5

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

**Agata217**| Posted: 01-03-2022

# Similar questions

Python counting elements of a list within a list

Say I have the following list:
L=[ [0,1,1,1],[1,0,1,1],[1,1,0,1],[1,1,1,0] ]
I want to write a code will take a list like this one and tell me if the number of '1s' in each individual list is equal to some number x. So if I typed in code(L,3) the return would be "True" because each list within L contains 3 '1s'. But if I entered code(L,2) the return would be "False". I'm new to all progr...

for loop - Counting elements of a list in Python

I am trying to define a function that takes two inputs, a list and an item (could be a string, int, float) and it returns the number of times the item appears in a list. Here's my code:
def count(sequence,item):
for all x in sequence:
if x != item:
while x in sequence:
sequence.remove(x)
return len(sequence)
however, this only deletes the first e...

Counting elements in a list of lists in python

Hope u can help me w/ this python function:
def comparapal(lista):#lista is a list of lists where each list has 4 elements
listaPalabras=[]
for item in lista:
if item[2] in eagles_dict.keys():# filter the list if the 3rd element corresponds to the key in the dictionary
listaPalabras.append([item[1],item[2]]) #create a new list with elements 2 and 3
The listaPalabras result...

python - Counting elements in a list using a while loop

This question already has answers here:

python - Counting number of ways to select unique elements from list of lists

I'm having trouble with SPOJ Problem 423: Assignments.
The problem asks me to count the number of possible assignments for n unique topics to n unique students so that each student gets exactly one topic that he/she likes. I have come up with a way to parse the input into a list of lists called preferences. Each inner list is a list of t...

python - Counting number of elements in nested list

Im trying to count the number of elements in a nested list, the list looks like this:
[(1944, ['Hughes H']),
(1940, ['Hill DK', 'Crawford GN', 'Greene HS', 'Myers J', 'Burr GO']),
(1941,
['McClung CE',
'Sumner FB',
'Gates RR',
'Lewis WH',
'Haas O',
'Haas O',
'Gould BS',
'Tytell AA',
'Hatch MH']),
(1942,
['Gaffron H',
'Gardner FT',
'Edwards PR',
'Bruner DW',
'Lake N...

python - Counting list elements using `set`

In an older post (Python: count repeated elements in the list), I noticed two replies (answer 3 and 5) that use set to count repeated elements of a list.
In a question I asked myself recently (

python list counting elements

I have a code as below
How can I find that abc is a list made up of lists?
Whats wrong with my map function?
I want my function to return count of each element in my input list divided by length of my list.
Something like
{'brown': 0.16666666666666666, 'lazy': 0.16666666666666666, 'jumps': 0.16666666666666666, 'fox': 0.16666666666666666, 'dog': 0.16666666666666666, 'quick': 0.166...

python - Counting elements in list

Let's say I have a list of customer IDs and a category of item that he buys:
[ [ID0 , 0], [ID1, 1], ... ]
A customer can appear more than once, and it is also possible that he buys the same type of item more than once.
For example, it is possible that we have [ID0, 1], [ID0, 2], [ID0, 1], [ID1, 1], ... somewhere in our list.
I want to construct a list so that list[0] = customer ID and list[1...

python - Counting similar elements from a table

I have a table where the digits represents the something like a score where the alphabets are something like names. Example, in the first list, X scores 1 and Y scores 1.
L = [['X','Y','1','1'],['C','A','1','2'],['X','Z','2','2']]
My aim is to find similar results between two teams. Example, X had a draw with Y in the first list and also X had a draw with Z in the third. That makes my outp...

python - How to Search and Counting Whether the Set of Elements in List

Below is the code that I search and count the pos_xist named list that holds the crawled element of en.wiktionary.org. The list holds the possible Part of Speech tag (with something not pos too) of wiktionary, and I search that list only to count how many of them in the list.
How can I shorten this code below in a more concise way?
count = 0
for i in range(0,10): #assumed maximum count of p...

python - counting elements in a list of tuples with added weight per item

I have a list of tuples:
for i, item in enumerate(tags_and_weights):
tags = item[0]
weight = item[1]
which prints:
1 (['alternative country', 'alternative pop', 'alternative rock', 'art rock', 'brill building pop', 'country rock', 'dance rock', 'experimental', 'folk', 'folk rock', 'garage rock', 'gbvfi', 'indie rock', 'jangle pop', 'lo-fi',...

python - Counting more elements then it should be

I'm learning OpenCV with Python, and I want to learn how to count objects/elements in an image.
I wrote a code for counting, but I get wrong results. There are 12 elements in the image, and I get 40, but also some elements are not counted.
I do not know what am I doing wrong.
This is the code that I have:
import cv2
img = cv2.imread('slika.jpg')
gray = cv2.cvtColor(img, cv2.COLOR_BG...

python - Counting the elements inside a list of list

I have a list of lists as follows
[
['DDX11L1', 'lincRNA', 'chr1', 11869, 14409],
['WASH7P', 'lincRNA', 'chr1', 14404, 29570],
['MIR1302-2HG', 'lincRNA', 'chr1', 29554, 31109],
['FAM138A', 'lincRNA', 'chr1', 34554, 36081],
['OR4G4P', 'unprocessed_pseudogene', 'chr2', 52473, 53312],
['DDX11L1', 'transcribed_unprocessed_pseudogene', 'chr2', 11869, 14409],
['WASH7P',...

python - Counting the number of elements in a list that contain more 0's than 1's

i'm new to python programming and my task is to tell how many binary values of the list there are where the number of 0's is grater than 1. The data for this task is in a text file, I've opened the file and put every line of text into separet value in list.
binary = list()
file = 'liczby.txt'
with open(file) as fin:
for line in fin:
binary.append(line)
print(*binary, sep = "\n")

python - TLE on counting the number of elements within the specified ranges in a list

There is an unsorted list a and a list of ranges like ranges = [(10, 20), (30, 50), (15, 35) ...]. The maximum value in a is uint64_t. The goal is to count the number of elements for each range. The normal solution is quite intuitive, just count the elements within the range and print the result. But the question is from a Online Judge. I tired sereval solutions, but for ...

python - Counting a different range elements in list

I have a list of grades ranging from between 1 and 100.
I need to find the following solution in PYTHON
0-10 0
10-20 5 *****
30-40 7 *******
40-50 8 ********
And so on up to 100. 0-10 has not instances in the list. The number and * represent how many grades are in the category within the list.
I have been told to create a list to of the total grades per q...

python - Counting elements in a matrix

I have this matrix:
matrix = [[a,r],[b,r],[c,r],[c,t,n],[b,t,n],[b,a]]
I want to count how many times did "n" appear in the matrix, but there is a condition. If the first letter is next to an "a" or an "r", it doesn't count as "n" appeared.
For example, in this list "n" appeared one time, because we have to discount the second time it appeared, due to the fact that the letter "b" later app...

python - Counting elements that appear only one time in a matrix

I have a list:
l = [['a', []], ['b', []], ['c', []], ['d', ['c']], ['e', ['d']], ['f', []], ['g', ['f', 'a', 'e']], ['h', ['g']]]
I want to count how many times an element doesn't appear in another list, for example in this list it would be b and h.
These are the only elements that appear only one time in all the list
, so the function would return 2.
Another example:
...

python - Counting the total number of elements in a csv file

Looking to count the total number of elements in a CSV file using Pandas in Python. So if a csv file has 500 elements, I would want to return 500.
df = pd.read_csv(fileName)
tick = df.index(["EventID"])
ticketNum = tick.size
print("There were", ticketNum, " film permits.")
Attempted to use index.size but unfortunately does not work. Is there any other method to...

Python counting elements of a list within a list

Say I have the following list:
L=[ [0,1,1,1],[1,0,1,1],[1,1,0,1],[1,1,1,0] ]
I want to write a code will take a list like this one and tell me if the number of '1s' in each individual list is equal to some number x. So if I typed in code(L,3) the return would be "True" because each list within L contains 3 '1s'. But if I entered code(L,2) the return would be "False". I'm new to all progr...

for loop - Counting elements of a list in Python

I am trying to define a function that takes two inputs, a list and an item (could be a string, int, float) and it returns the number of times the item appears in a list. Here's my code:
def count(sequence,item):
for all x in sequence:
if x != item:
while x in sequence:
sequence.remove(x)
return len(sequence)
however, this only deletes the first e...

Counting elements in a list of lists in python

Hope u can help me w/ this python function:
def comparapal(lista):#lista is a list of lists where each list has 4 elements
listaPalabras=[]
for item in lista:
if item[2] in eagles_dict.keys():# filter the list if the 3rd element corresponds to the key in the dictionary
listaPalabras.append([item[1],item[2]]) #create a new list with elements 2 and 3
The listaPalabras result...

Counting unique elements in sections of .csv columns (Python)

I have a .csv file of geological formations and occurrences of fossil species at each formation. Each fossil has its own row in the .csv file, with the formation name included in that row.
The code I wrote below printed out the number of formation occurrences just fine.
import csv
from collections import Counter
out=open("BivalviaGRDWIS.csv", "rb")
data=csv.reader(out)
data.next()
data=[row for ro...

python - Counting elements in a list using a while loop

This question already has answers here:

python - Counting number of ways to select unique elements from list of lists

I'm having trouble with SPOJ Problem 423: Assignments.
The problem asks me to count the number of possible assignments for n unique topics to n unique students so that each student gets exactly one topic that he/she likes. I have come up with a way to parse the input into a list of lists called preferences. Each inner list is a list of t...

python - Counting number of elements in nested list

Im trying to count the number of elements in a nested list, the list looks like this:
[(1944, ['Hughes H']),
(1940, ['Hill DK', 'Crawford GN', 'Greene HS', 'Myers J', 'Burr GO']),
(1941,
['McClung CE',
'Sumner FB',
'Gates RR',
'Lewis WH',
'Haas O',
'Haas O',
'Gould BS',
'Tytell AA',
'Hatch MH']),
(1942,
['Gaffron H',
'Gardner FT',
'Edwards PR',
'Bruner DW',
'Lake N...

python - Counting list elements using `set`

In an older post (Python: count repeated elements in the list), I noticed two replies (answer 3 and 5) that use set to count repeated elements of a list.
In a question I asked myself recently (

arrays - python; counting elements of vectors

I would like to count and save in a vector a the number of elements of an array that are greater than a certain value t. I want to do this for different ts.
eg
My vector:c=[0.3 0.2 0.3 0.6 0.9 0.1 0.2 0.5 0.3 0.5 0.7 0.1]
I would like to count the number of elements of c that are greater than t=0.9, than t=0.8

python list counting elements

I have a code as below
How can I find that abc is a list made up of lists?
Whats wrong with my map function?
I want my function to return count of each element in my input list divided by length of my list.
Something like
{'brown': 0.16666666666666666, 'lazy': 0.16666666666666666, 'jumps': 0.16666666666666666, 'fox': 0.16666666666666666, 'dog': 0.16666666666666666, 'quick': 0.166...

Counting all the keys pressed and what they are (python)

I'd like to create a map of the number of presses for every key for a project I'm working on.
I'd like to do this with a Python module. Is it possible to do this in any way?

Counting removed items in a Set in Python

Given two sets
a = [5,3,4,1,2,6,7]
b = [1,2,4,9]
c = set(a) - set(b)
# c -> [5,3,6,7]
is it possible to count how many items were removed from set 'a' ?

python - Counting problem: possible sudoko tables?

I'm working on a sudoko solver (python). my method is using a game tree and explore possible permutations for each set of digits by DFS Algorithm.
in order to analyzing problem, i want to know what is the count of possible valid and invalid sudoko tables?
-> a 9*9 table that have 9 one, 9 two, ... , 9 nine.
(this isn't exact duplicate by

list - Python - counting sign changes

I have a list of numbers I am reading left to right. Anytime I encounter a sign change when reading the sequence I want to count it.
X = [-3,2,7,-4,1,-1,1,6,-1,0,-2,1]
X = [-, +, +, -, +, -, +, +, -, -,-,+]
So, in this list there are 8 sign changes.
When Item [0] (in this case -3) is negative it is considered a sign change. Also, any 0 in the list is considered

python - Counting vowels

Can anyone please tell me what is wrong with this script. I am a python newb but i cant seem to figure out what might be causing it not to function.
def find_vowels(sentence):
"""
>>> find_vowels(test)
1
"""
count = 0
vowels = "aeiuoAEIOU"
for letter in sentence:
if letter in vowels:
count += 1
print count
if __name__ == '__main__':
import...

email - Counting the number of messages in an e-mail account with python

is there any way, in Python, to have access to an e-mail account (I'll need this for gmail but better if any works) and be able to see the number of messages in the inbox (maybe even unread messages only)?
Thank you.

python - Counting non-zero elements within each row and within each column of a 2D NumPy array

I have a NumPy matrix that contains mostly non-zero values, but occasionally will contain a zero value. I need to be able to:
Count the non-zero values in each row and put that count into a variable that I can use in subsequent operations, perhaps by iterating through row indices and performing the calculations during the iterative process.
Count the non-zero values in each co...

python - Counting content only in HTML page

Is there anyway I can parse a website by just viewing the content as displayed to the user in his browser? That is, instead of downloading "page.htm"l and starting to parse the whole page with all the HTML/javascript tags, I will be able to retrieve the version as displayed to users in their browsers. I would like to "crawl" websites and rank them according to keywords popularity (viewing the HTML source version is problem...

python - Quick counting with linked Django Models

I've got a stack of Models something like this (I'm typing it out in relative shorthand):
class User:
pass
class ItemList:
pass
# A User can have more than one ItemList
# An ItemList can have more than one User
# Classic M2M
class ItemListOwnership:
user = fk(User)
itemlist = fk(ItemList)
# An ItemList has multiple Items
class Item:
itemlist = fk(ItemList)
What ...

python - counting the word length in a file

So my function should open a file and count the word length and give the output. For example,
many('sample.txt')
Words of length 1: 2
Words of length 2: 6
Words of length 3: 7
Words of length 4: 6
My sample.txt file contains:
This is a test file. How many words are of length one?
How many words are of length three? We should figure it out!
Can a function do this?
My...

# Still can't find your answer? Check out these communities...

PySlackers | Full Stack Python | NHS Python | Pythonist Cafe | Hacker Earth | Discord Python