Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Combining a list of ranges in python

What is the easiest way to construct a list of consecutive integers in given ranges, like this?

[1,2,3,4,5,6,7,  15,16,17,18,19,  56,57,58,59]

I know the start and end values of each group.
I tried this:

ranges = (  range(1,8),
            range(15,20),
            range(56,60)  )
Y = sum( [ list(x) for x in  ranges ] )

which works, but seems like a mouthful. And in terms of code legibility, the sum() is just confusing. In MATLAB it’s just

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Y = [ 1:7, 15:19, 56:59 ]

Is there an better way? Can use numpy if easier.

Bonus question

Can anybody explain why it doesn’t work if I use a generator for the sum?

Y = sum( (list(x) for x in ranges) )

TypeError: unsupported operand types for +: ‘int’ and ‘list’

Seems like it doesn’t know the starting value should be [] rather than 0!

>Solution :

The matlab syntax has it’s equivalent in with numpy.r_:

import numpy as np

np.r_[1:7, 15:19, 56:59]

output: array([ 1, 2, 3, 4, 5, 6, 15, 16, 17, 18, 56, 57, 58])

For a list:

np.r_[1:7, 15:19, 56:59].tolist()

output: [1, 2, 3, 4, 5, 6, 15, 16, 17, 18, 56, 57, 58]

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading