1

I have two lists a=[10,5,6,8] and b=[1,3]. How can I use the latter as a subscript of the former? I.e. I would like to extract the second and fourth element of a.

Put otherwise, in Matlab I would use

v = [16 5 9 4 2 11 7 14];

v([1 5 6])      % Extract the first, fifth, and sixth elements
>>  ans =
        16   2   11

How can I do the same in Python?

user3658425
  • 119
  • 7
  • 1
    If you're coming from Matlab, will you be using these lists for matlab-like array operations? – DSM Jun 08 '14 at 16:42
  • 1
    To add a note, array index starts from 0 in python. – shahkalpesh Jun 08 '14 at 16:42
  • Take a look at http://stackoverflow.com/questions/18272160/access-multiple-elements-of-list-knowing-their-index –  Jun 08 '14 at 16:43
  • 1
    @shahkalpesh I think they understand that, as the `[1,3]` corresponds with the explanation of *I would like to extract the second and fourth element* – Jon Clements Jun 08 '14 at 16:43
  • @JonClements: My comment is based on the question where v[1, 5, 6] returns 16, 2, 11 in matlab. In python, it will return 5, 11, 7 – shahkalpesh Jun 08 '14 at 16:45
  • @shahkalpesh good point... well made... I retract my comment somewhat :) – Jon Clements Jun 08 '14 at 16:46

5 Answers5

7

You can use operator.itemgetter to do it:

from operator import itemgetter

a=[10,5,6,8]
b=[1,3]
res = itemgetter(*b)(a)
# (5, 8)
Jon Clements
  • 138,671
  • 33
  • 247
  • 280
6

You can use a list comprehension like so:

>>> a = [10, 5, 6, 8]
>>> b = [1, 3]
>>> [a[x] for x in b]
[5, 8]
>>>
3

numpy supports indexing with arrays, as well as a bunch of other array and matrix operations, in Matlab style. Consider using it for computationally intensive tasks:

In [1]: import numpy as np

In [2]: a = np.array([10,5,6,8])

In [3]: b = np.array([1,3])

In [4]: a[b]
Out[4]: array([5, 8])
Lev Levitsky
  • 63,701
  • 20
  • 147
  • 175
  • While the answer is helpful, numpy isnt part of standard module. So, it will be downloading something for the functionality OP asked. – shahkalpesh Jun 08 '14 at 16:43
  • 1
    @shahkalpesh it's fine to assume that if coming from matlab, the OP will either want or already have installed numpy/scipy/pandas etc... – Jon Clements Jun 08 '14 at 16:45
  • @JonClements: I dont have that background to assume things. List comprehension is built in, so it is straight forward. – shahkalpesh Jun 08 '14 at 16:46
2
l=[1 5 6]
v = [16 5 9 4 2 11 7 14];
[v[i] for i in l]

you can try like this

it can be explained like this

for i in l:
    print v[i]
sundar nataraj
  • 8,524
  • 2
  • 34
  • 46
2
a=[10,5,6,8]
b=[1,3]

ex = [a[i] for i in b]
print(ex) # [5, 8] 
timgeb
  • 76,762
  • 20
  • 123
  • 145