Why python has explicit enumeration

People (like me at the beginning) are wondering about python’s convention that numbering in an iteration has to be explicit. Let’s take this example:

seq = [42, 3.14159, 2.71828]

for i in seq:

# prints "42", "3.14159" and "2.71828" on each line

This example uses a list seq. There is no way to access the index the iteration is currently in. You have to use the enumerate() function explicitly.

seq = [42, 3.14159, 2.71828]

for nr, i in enumerate(seq):
    print("{}: {}".format(nr, i))

# prints "0: 42", "1: 3.14159" and "2: 2.71828" on each line

PHP provides the index of the iteration syntactically.

  $seq = array(42, 3.14159, 2.71828);

  foreach ($seq as $value) {
    echo $value, "\n";
  // prints "42", "3.14159" and "2.71828" on each line
  foreach ($seq as $key => $value) {
    echo $key.': ', $value, "\n";
  // prints "0: 42", "1: 3.14159" and "2: 2.71828" on each line

Javascript returns always the index and you can use it as an key:

var seq = [42, 3.14159, 2.71828];

for (var index in seq) {
    document.write('' + index + ': ' + seq[index] + "\n");

He have different philosophies here for different programming languages. But there is a difference between (Javascript and PHP) and python. Whereas Javascript and PHP frequently use hashmaps (in Javascript we actually create an object, not Array), python uses linked lists to implement its data type. The important difference between a linked list/arrays and hashmaps is that the first two data type don’t explicitly know the concept of indexing. In arrays the elements are positioned sequentially. The iterating instance has to increment the index themselves, because the index is not stored in the data type. The same applies to linked lists, which only stores its pointers to the successor/predecessor.

So overall the python internals do not know the index of the current element and you can use enumerate() to explicitly create an incrementing index. PHP and Javascript always need those indices to access a value.

Why python has explicit enumeration