'What is a natual way to count the number of things in python?

In python, I learned that it is natural to start an index set from 0. I.e.) if there is an array, the first element is not the 1st but the 0th element.

My question is what about when you count the number of things. For example, if there is an array, {3, -1, 2, 5, -7}, what is the number of the elements of the array? Is it 5 elements or 4 elements? Is the number of the elements 0 or 1, when there is {3}, an array with a single element?

I'm not a computer engineer so have less knowledge about programming.



Solution 1:[1]

if there is an array, {3, -1, 2, 5, -7}, what is the number of the elements of the array? Is it 5 elements or 4 elements? Is the number of the elements 0 or 1, when there is {3}, an array with a single element?

The list

a = []

is an empty list and has 0 elements.

The list

a = [1]

is a nonempty list and has 1 element. The first and only element can be accessed via a[0].

The list

a = [1, 2, 3, 4, 5] 

is a nonempty list and has 5 elements. The first element is accessed via a[0], the second by a[1], the third by a[2], ..., the fifth by a[4].

In python, I learned that it is natural to start an index set from 0. I.e.) if there is an array, the first element is not the 1st but the 0th element.

The first element is the first element. In computer science (not just in Python), we often use zero-based indexing whereby the initial/first element of a sequence is assigned the index 0, the second element is assigned the index 1, and so on.

In general, with zero-based indexing, given some nonempty sequence, the

nth element is assigned the index n - 1

When we want to access the third element of a, we know that the third element is assigned the index 2 and so we write a[2] to access it.

Solution 2:[2]

When you have an array like this

>>> array = [ 3, -1, 2, 5, -7]

Now I print the number of elements of the array with the help of the len function

>>> print(len(array))
5

the result is 5, since array programming always starts at index 0. At first it can seem confusing.

[ 3, -1, 2, 5, -7] -> [0,1,2,3,4]

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 TylerH
Solution 2