2

Given

mylist = ["a", "b", "c"]

how can I subset elements 0 and 2 (i.e., ["a", "c"])?

Mark
  • 29
  • 1
  • 7
    Surely you don't have trouble writing `[mylist[0], mylist[1]]`? So please describe what do you *really* want to do. –  Jul 31 '11 at 22:50
  • I want something like mylist[0,2] (where [0,2] is a list of the element positions I want). – Mark Jul 31 '11 at 22:58

4 Answers4

8

Although this is not the usual way to use itemgetter,

>>> from operator import itemgetter
>>> mylist = ["a", "b", "c"]
>>> itemgetter(0,2)(mylist)
('a', 'c')

If the indices are already in a list - use * to unpack it

>>> itemgetter(*[0,2])(mylist)
('a', 'c')

You an also use a list comprehension

>>> [mylist[idx] for idx in [0,2]]
['a', 'c']

or use map

>>> map(mylist.__getitem__, [0,2])
['a', 'c']
John La Rooy
  • 295,403
  • 53
  • 369
  • 502
  • 7
    please, don't tell people to use map that way. BTW, don't tell people to use map... –  Aug 01 '11 at 00:35
  • 1
    @Franklin, `map` is still a solid part of Python. It's still a builtin in Python3 and has even been improved to return an iterator instead of a list. – John La Rooy Aug 01 '11 at 01:24
  • 1
    Yeah if it's so solid then why it changed? And why Guido wanted to remove it? –  Aug 01 '11 at 01:31
  • Franklin, why don't you read [this question](http://stackoverflow.com/questions/1247486/python-list-comprehension-vs-map)? You might see when and why someone might use map instead of list comprehension. – Utku Zihnioglu Aug 01 '11 at 01:49
  • 1
    List comprehensions are much more straightforward. Can't see a single reason to use map. –  Aug 01 '11 at 03:50
  • @Franklin, the point of the answer @utku links to is that the use of map is quite polarizing. I think people learning Python would see the LC here and think it is more readable than map and agree with you. However `map` is commonly used in many other programming languages, so people coming from those languages may find `map` more natural than the LC. The more important thing to me is that neither method has many places for bugs to creep in compared to say, doing the same thing in C – John La Rooy Aug 01 '11 at 04:13
  • @Franklin, I consider `map` more legible in some cases, for example I prefer `map(int, ["1", "2", "3"]` over `[int(x) for x in ["1","2","3","4"]]`. – Michał Bentkowski Aug 01 '11 at 07:07
3

For fancy indexing you can use numpy arrays.

>>> mylist = ["a", "b", "c"]
>>> import numpy
>>> myarray = numpy.array(mylist)
>>> myarray
array(['a', 'b', 'c'], 
      dtype='|S1')
>>> myarray[[0,2]]
array(['a', 'c'], 
      dtype='|S1')
Glorfindel
  • 21,988
  • 13
  • 81
  • 109
SiggyF
  • 22,088
  • 8
  • 43
  • 57
2

Here's one solution (among many):

[mylist[i] for i in [0, 2]]
Marcelo Cantos
  • 181,030
  • 38
  • 327
  • 365
1

If you want every second one, mylist[::2].

Cat Plus Plus
  • 125,936
  • 27
  • 200
  • 224