DEV Community

Discussion on: Python for JavaScript Developers

Collapse
 
xaddict profile image
Luuk Lamers

Aren't they exactly like JavaScript's for...in loops? developer.mozilla.org/en-US/docs/W...

The only difference seems to be Python doesn't do prototypes so you don't have to use hasOwnProperty to check the origin of an object's variables

Collapse
 
tomleo profile image
Tom Leo

"The for...of statement creates a loop iterating over iterable objects (including Array, Map, Set, String, TypedArray, arguments object and so on), invoking a custom iteration hook with statements to be executed for the value of each distinct property."

In Python you can iterate over iterators or generators. When the end of iteration is reached, an exception is raised that triggers the loop to stop. To me, for..of seems closer to python for..in.

Thread Thread
 
bmarkovic profile image
Bojan Markovic • Edited

You're right.

for .. in iterates over key, i.e. it's comparable to something like:

for (let i = 0, o = Object.keys(X); i < o.length; i++, x=o[i]) { .. }

whereas for .. of iterates over iterables i.e. it's roughly comparable to something like:

for (let x, o; o && o.done === false; o = X.next(), x = o && o.value) { .. }

It's slightly more complicated than that because it implicitly converts some objects, such as Arrays or Maps, to iterables.

JavaScript since ES6 also has generators and iterators that work somewhat similar. There are no exceptions, tho, because iterator interface (that generators also need to adher to in general) returns an object on calls to .next() that is of form {done, value}. When done is false you've reached the end of the iterable.

Thread Thread
 
cben profile image
Beni Cherniavsky-Paskin

But note that in python for key in {1: 10, 2: 20}: iterates over dictionary's keys.

You can use for value in d.keys():, for (key, value) in d.items(): and (redundant) for k in d.keys():.
These methods exist in both Python 2 and 3, though with some differences (see python.org/dev/peps/pep-3106/).

Thread Thread
 
tomleo profile image
Tom Leo

You can drop the parenthesis i.e. for k, v in thing.items(). You only need parenthesis for comprehension i.e. {k: v for (k,v) in thing.items()} or [(k,v) for (k,v) in thing.items()]