Differences between Python and JavaScript in relation to arrays?

2

I'm having a hard time because in JavaScript it was possible to do this:

const x = []
x[0] = 1
x[1] = 2

But in Python when I create an empty list and try to make a statement it says the index is out of range. I can work around the append() method but I wanted to know if it has a way of doing it like in JavaScript.

    
asked by anonymous 07.10.2017 / 15:52

1 answer

5

Although syntax is identical, semantically what is produced with it is very different in every language.

In Pyhton this code actually produces a list. In JavaScript what you are creating is a dictionary, also known as map or array associative.

In Python there is another syntax for creating a dictionary.

In JavaScript there is an optimization to treat a dictionary as array whenever possible. In fact this is the term used, but it looks more like a list than an array .

An array or a list is characterized by having the elements in sequence and densely, being able to access them with complexity O (1), that is, any access is done in a direct way .

A dictionary is sparse and has no order in the elements. Although accessing each element in O (1), is not directly, it is necessary to calculate where the key is, since it has no order and can not even exist.

A dictionary typically creates a name key automatically when it tries to put a value in a non-existent key. When you do this it will probably inhibit optimizations to treat the dictionary as a list, but it depends on implementation.

As in Python there is not this confusion of concepts in the same syntax need to be explicit of what you want.

If you can use a list, use it, even if you have to adapt the code a bit. If it is really necessary to create a dictionary, then go for it. But do not create the dictionary just to look like JS or just to write seemingly simpler code. A list is always more advantageous than a dictionary if the elements are used in order with a complete sequence of numbers.

Eventually even when it looks like a dictionary it may be more advantageous for performance and memory to use a list in place of the dictionary even when some elements are missing.

    
07.10.2017 / 17:29