problem about list indexing

John Machin sjmachin at lexicon.net
Sun Nov 26 04:35:54 EST 2006


hollowspook wrote:
> Hi, there
>
> a = range(100)
>
> if I want to use No 7, 11, 56,90 in a, then the only way I do is [a[7],
> a[11], a[56], a[90]].
> Is there any other way?
>

I presume a = range(100) is just an indication that a is a list -- the
literal answer to your question as asked is simply [7, 11, 56, 90]

In the general case that a is *any* list (or anything else that
supports the index protocol, e.g. a string, a tuple, an array.array
instance, or some instance of a so-written class), you can use a "list
comprehension". Example:

| >>> a = 'qwertyuiopasdfghjklzxcvbnm'
| >>> [a[x] for x in [25, 0, 13, 1]]
| ['m', 'q', 'f', 'w']

Do try and find "list comprehension" in the manual and in your book or
tutorial. It's useful for much more than the above.

HTH,
John




More information about the Python-list mailing list