What about an EXPLICIT naming scheme for built-ins?

Carlos Ribeiro carribeiro at gmail.com
Sun Sep 5 16:41:55 EDT 2004


Well. As said, almost done. One thing that I promise is that, whatever
comes out of this, I promise to summarize a faq-like answer to "why
are sorted() and [i]reversed() named like that".

For now I´ll focus on a single issue now:

My idiom:
reverse_list = [x for x in reversed(mylist)]

Alex's idiom:
reversed_list = list(reversed(mylist))

There is no doubt that Alex's idiom is *much* more efficient than
mine. However, I was left wondering on why didn't I come up with it
first time -- it's obvious once you see it, but still, for some
reason, the list comprehension was more intuitive for me. I don't know
about the rest of Pythoneers, specially newbies, but understanding
*why* did I came up with my version may help to illustrate the mental
model surrounding iterators.

My explanation is that iterators and list comprehensions are
conceptually similar. reversed() or (ireversed(), for that matter)
returns an iterator, so it's relatively simple to use it inside a list
comprehension.

list(), on the other hand, is a built in that takes a sequence as an
argument. And guess what? The argument does not need to be a "true"
sequence or tuple. According to the Python manual,

"list( [sequence])  -- Return a list whose items are the same and in
the same order as sequence's items. sequence may be either a sequence,
a container that supports iteration, or an iterator object. "

So almost anything will do it, but for some reason, I found the list
comprehension version to be more intuitive. Guess I have to read the
manual more often :-)

-- 
Carlos Ribeiro
Consultoria em Projetos
blog: http://rascunhosrotos.blogspot.com
blog: http://pythonnotes.blogspot.com
mail: carribeiro at gmail.com
mail: carribeiro at yahoo.com



More information about the Python-list mailing list