I am reading Joel Grus's data science from scratch book and found something a bit mysterious. Basically, in some sample code, he wrote
a = [1, 2 ,3 ,4]
xs = [i for i,_ in enumerate(a)]
Why would he prefer to do this way? Instead of
xs = range(len(a))
Python uses zero-based indexing. That means, the first element(value 'red') has an index 0, the second(value 'green') has index 1, and so on.
Python also allows you to index from the end of the list using a negative number, where [-1] returns the last element. This is super-useful since it means you don't have to programmatically find out the length of the iterable in order to work with elements at the end of it.
Answer: personal preference of the author. I find
[i for i, _ in enumerate(xs)]
clearer and more readable than
list(range(len(xs)))
which feels clunky to me. (I don't like reading the nested functions.) Your mileage may vary (and apparently does!).
That said, I am pretty sure I didn't say not to do the second, I just happen to prefer the first.
Source: I am the author.
P.S. If you're the commenter who had no intention of reading anything I write about Python, I apologize if you read this answer by accident.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With