2

Given

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

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

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

4 Answers 4

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']
Sign up to request clarification or add additional context in comments.

7 Comments

please, don't tell people to use map that way. BTW, don't tell people to use map...
@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.
Yeah if it's so solid then why it changed? And why Guido wanted to remove it?
Franklin, why don't you read this question? You might see when and why someone might use map instead of list comprehension.
List comprehensions are much more straightforward. Can't see a single reason to use map.
|
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')

1 Comment

@Mark, If answer is perfect for you, you should mark it as accepted. to do that, simply click on the tick outline.
2

Here's one solution (among many):

[mylist[i] for i in [0, 2]]

Comments

1

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.