Subset a list with two non-consecutive slices in Python

Advertisements

I’m working with a list in Python and I need to extract elements with indices from 0 to 3 and from 5 to 7 ([0:3] and [5:7]). It could be done by using slicing and concatenation:

target_list = [1, 2, 3, 4, 5, 6, 7, 8, 9]
subset_indx = list(range(3)) + list(range(4, 7)) 
subset_list = [target_list[i] for i in subset_indx]
print(subset_list)  # Output: [1, 2, 3, 5, 6, 7]

I’m curious if there’s a way to achieve this functionality in Python similar to how it’s done in R.

targetList <- c(1, 2, 3, 4, 5, 6, 7, 8, 9)
subsetList <- targetList[c(1:3, 6:7)]

I’d appreciate any insights or reproducible code examples demonstrating Pythonic equivalents.

>Solution :

Method 1: slicing and concatenation:

subset_list = target_list[:3] + target_list[4:7]

Method 2: slicing and deletion:

subset_list = target_list[:7]
del subset_list[3]
# if more than 1 items need to be skipped over, you can also delete a slice, e.g.:
# del subset_list[3:6]

The first method is probably more Pythonic.

Leave a ReplyCancel reply