How to Convert Numeric String Range to a List in Python?

Python – Convert Numeric String Range to a List

To convert numeric string range like '4-9' to a list like [4, 5, 6, 7, 8, 9] in Python: split the string using hyphen as delimiter, convert the splits to integers, create a range using these integers, and then convert the range to a list.


In the following program, we read a string from user using input() function, and convert the given numeric string range to a list.

Python Program

#read input
x = input()

#split the string
a, b = x.split('-')
#convert string splits into integers
a, b = int(a), int(b)
#create a range from the given values
result = range(a, b + 1)
#convert the range into list
result = list(result)

#print result to cosole

Output #1

[4, 5, 6, 7, 8, 9]

Output #2

[1, 2, 3, 4, 5]

Output #3

[125, 126, 127, 128]



In this Python Tutorial, we learned how to convert a given numeric string range into a list of numbers.