Skip to content

Instantly share code, notes, and snippets.

@nmpeterson
Last active December 18, 2015 18:09
Show Gist options
  • Save nmpeterson/5823235 to your computer and use it in GitHub Desktop.
Save nmpeterson/5823235 to your computer and use it in GitHub Desktop.
A function to convert a list of integers into a string of ranges of consecutive values.
def list_to_ranges(in_list):
''' Convert a list of integers into a string of ranges of consecutive values. '''
l = in_list[:]
l.sort()
range_str = str(l[0])
for i in xrange(1,len(l)-1): # Handle first & last separately
if l[i] == l[i-1]+1 and l[i] == l[i+1]-1:
pass
elif l[i] != l[i-1]+1:
range_str += ', ' + str(l[i])
else:
range_str += '-' + str(l[i])
if len(l) > 1:
if l[-1] == l[-2]+1:
range_str += '-' + str(l[-1])
else:
range_str += ', ' + str(l[-1])
del l
return range_str
# Example call:
list_to_ranges([1, 2, 3, 4, 5, 7, 8, 9, 21, 22, 23]) #=> '1-5, 7-9, 21-23'
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment