1

It's fairly simple to articulate problem, but I'm not 100% sure that I have my lingo right. Nonetheless, conceptually "cherry picking" is suitable to describe the slice I have in mind. This is because I simply want to access (cherry pick from all elements) two distant elements of a list. I tried this:

my_list[2,7]

So I was expecting it to return only 2 elements, but instead I got the error:

list indices must be integers, not tuples.

I searched this error, but I found it was actually a very general error and none of the problems that instigated this error were actually for my type of problem.

I suppose I could extract the elements 1 at a time and then merge them, but my gut tells me there is a more "pythonic" way about this.

Also a slightly more complicated form of this problem I ran into was building a new list from an existing list of lists:

new_list = []
for i in range(len(my_list)):
    new_list.append(my_list[i][2,7])
MSeifert
  • 145,886
  • 38
  • 333
  • 352
Arash Howaida
  • 2,575
  • 2
  • 19
  • 50

2 Answers2

5

Normally I would just use operator.itemgetter for this:

>>> my_list = list(range(10))
>>> import operator
>>> list(operator.itemgetter(2, 7)(my_list))
[2, 7]

It also allows getting an arbitrary amount of list elements by their indices.


However you can always use NumPy (that's an external package) and it's integer slicing for this (but it won't work for normal Python lists, just for NumPy arrays):

>>> import numpy as np
>>> my_arr = np.array(my_list)
>>> my_arr[[2, 7]]
array([2, 7])
MSeifert
  • 145,886
  • 38
  • 333
  • 352
1
In [1]: myList = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
In [2]: myList[2:8:5]
Out[2]: [2, 7]

myList[start:end:stride]

Hope this helps.

user3053452
  • 640
  • 1
  • 12
  • 38