rf7
rf7

Reputation: 2191

How to access non-consecutive slices of a list in Python

This is a rather basic question as I am new to Python coming from R.

In R we can access non consecutive slices in a vector or list like this:

> a = 1:10
> a[c(2:4, 7:9)]
[1] 2 3 4 7 8 9
> list_a = list(1:10)
> list_a[[1]][c(2:4, 7:9)]
[1] 2 3 4 7 8 9

I am trying to find out how to do the same with a list in Python.

E.g.

a = list(range(20))
a[1:4]
# returns
[1, 2, 3]
# but the following syntax creates an exception:
a[1:4, 7:9]

Your advice will be appreciated.

Upvotes: 0

Views: 1899

Answers (1)

Scott Hunter
Scott Hunter

Reputation: 49803

You could accomplish what you want in a[1:4,7:9] by using a[1:4]+a[7:9].

Upvotes: 1

Related Questions