3

I am asking this question related to this one:

Access multiple elements of list knowing their index

Basically if you have a list and want to get several elements you cannot just pass a list of indexes.

Example:

a = [-2,1,5,3,8,5,6]
b = [1,2,5]             # list of indexes 
a[b]                    #this doesn't work
# expected output: [1,5,5]

To solve this problem several options are proposed in the linked question:

Using list comprehension:

a = [-2,1,5,3,8,5,6]
b = [1,2,5]
c = [a[i] for i in b]

Using operator.itemgetter:

from operator import itemgetter 
a = [-2, 1, 5, 3, 8, 5, 6]
b = [1, 2, 5]
print itemgetter(*b)(a)

or using numpy arrays (which DO accept indexing with lists)

import numpy as np
a = np.array([-2, 1, 5, 3, 8, 5, 6])
b = [1, 2, 5]
print list(a[b])

My question is: Why normal lists don't accept this? This will not conflict the normal indexing [start:end:step] and will provide another way of accessing list elements without using external libraries.

I don't intend this question to attract opinion based answers but rather to know if there is an specific reason why this feature is not available in Python, or if it will be implemented in a future.

Community
  • 1
  • 1
  • Not sure to understand, are you aware of the slice notation to manipulate lists ? http://stackoverflow.com/questions/509211/explain-pythons-slice-notation – PyNico Feb 02 '17 at 11:03
  • @PyNico OP mentioned the slice notation in his question, but he's asking about getting multiple elements that can't be represented by a single slice – TidB Feb 02 '17 at 11:06
  • Ow, sorry i didn't understood then. I can't answer this question. – PyNico Feb 02 '17 at 11:09
  • Do you mean you want to get `[-2,1,5,3,8,5,6][1,2,5] => [1, 5, 5]`? – Andersson Feb 02 '17 at 11:26
  • 3
    What's wrong with `[a[i] for i in b]`? Seems simple enough to me. – Ben Feb 02 '17 at 12:06
  • @Anderson yes exactly. @ Ben I agree it's a simple method, but why not having the two ways? Many things can be done in different ways. My question is if there is some specific reason (limitation, language standard, etc...) to not implement this functionality. –  Feb 02 '17 at 13:23

2 Answers2

0

Another way we can get the expected output, and it might can be implemented into python function related with list.

a = [-2,1,5,3,8,5,6]
b = [1,2,5]
def getvalues(original_list, indexes_list):
    new_list = []
    for i in indexes_list:
        new_list.append(original_list[i])
    return new_list
result = getvalues(a, b)
print(result)
0

A simple and easy approach to do it can be done in a list comprehension:

a = [-2,1,5,3,8,5,6]
b = [1,2,5]

multi_index = lambda l1, l2: [l1[i] for i in l2]
>>> print(multi_index(a,b))
[1, 5, 5]
Pythoneer
  • 319
  • 1
  • 16