The Python Oracle

Counting array elements in Python

--------------------------------------------------
Hire the world's top talent on demand or became one of them at Toptal: https://topt.al/25cXVn
and get $2,000 discount on your first invoice
--------------------------------------------------

Take control of your privacy with Proton's trusted, Swiss-based, secure services.
Choose what you need and safeguard your digital life:
Mail: https://go.getproton.me/SH1CU
VPN: https://go.getproton.me/SH1DI
Password Manager: https://go.getproton.me/SH1DJ
Drive: https://go.getproton.me/SH1CT


Music by Eric Matyas
https://www.soundimage.org
Track title: Quiet Intelligence

--

Chapters
00:00 Counting Array Elements In Python
00:14 Accepted Answer Score 366
00:33 Answer 2 Score 4
00:45 Answer 3 Score 28
01:21 Answer 4 Score 2
01:36 Thank you

--

Full question
https://stackoverflow.com/questions/1874...

--

Content licensed under CC BY-SA
https://meta.stackexchange.com/help/lice...

--

Tags
#python #arrays

#avk47



ACCEPTED ANSWER

Score 366


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

Syntax:

len(myArray)

Eg:

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

Output:

3




ANSWER 2

Score 28


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.




ANSWER 3

Score 4


Or,

myArray.__len__()

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




ANSWER 4

Score 2


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)