Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

difference between ways to generate index list in python

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))
like image 848
nos Avatar asked Apr 15 '16 12:04

nos


People also ask

What are the types of indexing in Python?

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.

What does [- 1 :] mean in Python?

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.


1 Answers

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.

like image 105
Joel Avatar answered Sep 21 '22 14:09

Joel