1

need help on this

Example to select first 5 items from the below list
nums = [10, 20, 30, 40, 50, 60, 70, 80, 90]
nums[:5]
output = [10, 20, 30, 40, 50]

If I want my output like below. Expected output = [10,20,60,70,90]

Please let me know how to achieve this.

I am trying something like this nums[:1,5:6,8] nums[0,1,5,6,8]

Patrick Artner
  • 50,409
  • 9
  • 43
  • 69
JK1185
  • 109
  • 1
  • 8
  • 5
    Common slice notation does not allow for such complicated logic, you would have to do: `nums[:2] + nums[5:7] + nums[8:]` – user2390182 Dec 08 '20 at 12:12
  • 1
    The "duplicate" question is not a duplicate. This question is different - it asks about multi slices which are not mentioned in the dupe – Gulzar Dec 08 '20 at 12:26
  • @Patrick Artner please remove the duplicate tag for this question as i checked the Understanding slice notation question but no where it mentioned about + operater. It is just rhe basic which is not helping. Thanks – JK1185 Dec 08 '20 at 12:50
  • 1
    @Jk185 I added the dupe for the concattenating problem as well - you had problems with the slice syntax (_I am trying `nums[:1,5:6,8]`_) so that one popped out at first. – Patrick Artner Dec 08 '20 at 13:18
  • Here's another duplicate: [Multiple Slices With Python](https://stackoverflow.com/q/38895781/2745495) – Gino Mempin Dec 10 '20 at 10:30

2 Answers2

2

You could concatenate multiple 3 lists to achieve this, one composed of the first 3 elements, one with elements 60,70 and one with the last element like this:

nums = [10, 20, 30, 40, 50, 60, 70, 80, 90]
print(nums[:2] + nums[5:7] + nums[-1:])

# output [10,20,60,70,90]
Dan Ionescu
  • 3,135
  • 1
  • 12
  • 17
  • 2
    Thank you for your answer I am going to use your answer as it fits well with my issue. I was unaware of the + operator. – JK1185 Dec 08 '20 at 12:47
1

One way of indexing using arrays can be done using numpy

> pip install numpy

import numpy as np

nums = [10, 20, 30, 40, 50, 60, 70, 80, 90]
nums_np = np.array(nums)
inds = np.array([0,1,5,6,8])
result = nums_np[inds]
print(results)

Another way:

result = np.r_[nums_np[:2], nums_np[5:7], nums_np[8]]
Gulzar
  • 23,452
  • 27
  • 113
  • 201