Eric <[EMAIL PROTECTED]> writes:

> I'm learning Python (while coming from MATLAB). One question I have is
> that if I have a list with say 8 elements, and I want just a few of
> them how do I select them out. In MATLAB, if I just want the first,
> fifth and eighth element I might do something like this:
> 
> b = a([1 5 8]);
> 
> I can't seem to figure out a similar Python construct for selecting
> specific indices. Any suggestions?

Yes: the above code uses magic numbers which convey no semantic
meaning, and should instead use *named* elemets of a container. In
Python, that's done with a mapping type, which has the built-in type
of ‘dict’.

In other words: a list is best for sequences where any item is
semantically identical to any other, and you can (for example)
re-order all the elements in the list without changing their semantic
meaning. If, instead, you want semantic meaning, that's best done via
*names*, not magic numbers.

In your example, presumably the numbered elements above are being
selected because they, as distinct from the second, fourth, seventh,
et cetera, have specific semantic meaning. That's better represented
in Python by using a mapping type such as ‘dict’, that maps a
semantically-meaningful name (or, sometimes, some other identifying
object) to each value.

If you explain what it is you want to do (your example above gives no
clue), we can perhaps give more specific advice.

-- 
 \        “I saw a sign: ‘Rest Area 25 Miles’. That's pretty big. Some |
  `\                      people must be really tired.” —Steven Wright |
_o__)                                                                  |
Ben Finney
--
http://mail.python.org/mailman/listinfo/python-list

Reply via email to