0

In Python, say we have

L = ['a','b','c','d','e','f','g']

and I want to store the elements at indices 1,3,5,6 in another list. In a program like GAP, this is a one-liner:

>>> New_L = L{[1,3,5,6]};

['b', 'd', 'f', 'g']

I've always wondered: is there something like this in Python? Or is this only done roughly as follows:

New_L = []
for i in [1,3,5,6]:
    New_L.append(L[i])
Dan P.
  • 269
  • 2
  • 9
  • 1
    Numpy might have something for their arrays. Otherwise, if you want it succinct, you could just wrap that in a function. – Carcigenicate Dec 19 '19 at 23:28
  • 3
    as long as you have the indices stored in another container you can do some list comprehension `New_L = [L[ind] for ind in inds]` – fulaphex Dec 19 '19 at 23:29
  • Yeah I usually have a function defined for. I like the list comprehension suggestion -that works well thanks! – Dan P. Dec 19 '19 at 23:30
  • It is possible in Python to take a slice of a list e.g. `New_L = L[start:stop:step]` So, in your case it is `New_L = L[1::2]` – SarahJessica Dec 19 '19 at 23:34
  • 1
    As @Carcigenicate mentioned, [its possible with Numpy arrays as described here](https://www.geeksforgeeks.org/indexing-in-numpy/) – DarrylG Dec 19 '19 at 23:40

1 Answers1

2

It can be written as list comprehension in one line:

New_L = [L[i] for i in [1,3,5,6]]
Michael Butscher
  • 10,028
  • 4
  • 24
  • 25