4

What I want to do is reference several different ranges from within a list, i.e. I want the 4-6th elements, the 12 - 18th elements, etc. This was my initial attempt:

test = theList[4:7, 12:18]

Which I would expect to give do the same thing as:

test = theList[4,5,6,12,13,14,15,16,17]

But I got a syntax error. What is the best/easiest way to do this?

Bhargav Rao
  • 50,140
  • 28
  • 121
  • 140
lukehawk
  • 1,423
  • 3
  • 22
  • 48

3 Answers3

8

You can add the two lists.

>>> theList = list(range(20))
>>> theList[4:7] + theList[12:18]
[4, 5, 6, 12, 13, 14, 15, 16, 17]
LondonRob
  • 73,083
  • 37
  • 144
  • 201
Bhargav Rao
  • 50,140
  • 28
  • 121
  • 140
  • Thanks!! This seems so blatantly obvious... (But in my defense I just picked up python...) – lukehawk Jul 06 '15 at 18:56
  • Glad to be able to help you. All the best. (Pickup python asap :P ) – Bhargav Rao Jul 06 '15 at 18:57
  • How would i create a list? I am sorry. I am used to R, and in R, if i wanted just a sequence from 1 to 7, I could do something like theSeq = 1:7, which would generate an array of 1,2,3,4,5,6,7. How do I do this in python? – lukehawk Jul 06 '15 at 19:02
  • 1
    @lukehawk Take a look at the `range` function. You can read more about it [Python - Create list with numbers between 2 values?](http://stackoverflow.com/questions/18265935/python-create-list-with-numbers-between-2-values) – Bhargav Rao Jul 06 '15 at 19:04
2

You can also use itertools module :

>>> from itertools import islice,chain
>>> theList=range(20)
>>> list(chain.from_iterable(islice(theList,*t) for t in [(4,7),(12,18)]))
[4, 5, 6, 12, 13, 14, 15, 16, 17] 

Note that since islice returns a generator in each iteration it performs better than list slicing in terms of memory use.

Also you can use a function for more indices and a general way .

>>> def slicer(iterable,*args):
...    return chain.from_iterable(islice(iterable,*i) for i in args)
... 
>>> list(slicer(range(40),(2,8),(10,16),(30,38)))
[2, 3, 4, 5, 6, 7, 10, 11, 12, 13, 14, 15, 30, 31, 32, 33, 34, 35, 36, 37]

Note : if you want to loop over the result you don't need convert the result to list!

Mazdak
  • 105,000
  • 18
  • 159
  • 188
1

You can add the two lists as @Bhargav_Rao stated. More generically, you can also use a list generator syntax:

test = [theList[i] for i in range(len(theList)) if 4 <= i <= 7 or 12 <= i <= 18]
rlbond
  • 65,341
  • 56
  • 178
  • 228