Counting array elements in Python
--
Music by Eric Matyas
https://www.soundimage.org
Track title: Puzzle Game 2 Looping
--
Chapters
00:00 Question
00:24 Accepted answer (Score 360)
00:51 Answer 2 (Score 28)
01:38 Answer 3 (Score 20)
02:24 Answer 4 (Score 4)
02:42 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)