Then the steps can be broken down into smaller pieces if desired, without needing to re-store all of the content temporarily at every step along the way.
Python’s generator expressions also often make this kind of thing even clearer:
list(name for line in fileLines for name in line.split(','))
Ideally there would also be a nice iterator-producing “split” method/function for scanning through the string incrementally so that it would be unnecessary to construct a separate array for each split.
> not sure how that particular iterator version is an improvement
In this case it is not. But if you want to do more complicated things, you can do several steps with iterators, and then crystallize an array (or sometimes a single reduced result) at the end.
* * *
Edit: whoops I had it correct it in my python shell and then mindlessly typed it wrong into this conversation.
Apologies!
* * *
Also yes sure you should use a list comprehension at the end in the Python, but again if you use generator expressions you can keep working on them for several lines of streaming transformations without needing to actually construct any full list along the way.
* * *
As an example, instead of TFA’s min/max example, we can do something like:
In python you could use just a regular function with a for loop. You can do that in javascript too. But the versions using smaller components can be faster to write and more composable. Really depends what kind of style you like and what you are trying to do..
const min_max = function min_max(iterable) {
const it = iterable[Symbol.iterator]();
const {value, done} = it.next(); if (done) return;
let min = value, max = value;
for (let x of it) {
min = Math.min(min, x);
min = Math.max(max, x);
}
return [min, max];
}
min_max(readings);
Anywhere that would be appropriate for a generator in python can also be a generator in Javascript though.
Python’s generator expressions also often make this kind of thing even clearer:
Ideally there would also be a nice iterator-producing “split” method/function for scanning through the string incrementally so that it would be unnecessary to construct a separate array for each split.