How can I refer to values ​​from different ranges in a list?

I want to make a link to several different ranges from the list, i.e. I want 4-6 elements, 12-18 elements, etc. This was my initial attempt:

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

Which I would expect to do the same 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?

+4
source share
3 answers

You can add two lists.

>>> theList = list(range(20))
>>> theList[4:7] + theList[12:18]
[4, 5, 6, 12, 13, 14, 15, 16, 17]
+8
source

You can also use the itertoolsmodule:

>>> 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 the islicegenerator returns at each iteration, it works better than sorting a list in terms of memory usage.

.

>>> 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]

: , list!

+2

You can add two lists as indicated in @Bhargav_Rao. In a more general way, you can also use the list generator syntax:

test = [theList[i] for i in range(len(theList)) if 4 <= i <= 7 or 12 <= i <= 18]
+1
source

All Articles