Signup/Sign In

Converting a String Number Range with hyphen to a List of Numbers in Python

Posted in Programming   LAST UPDATED: AUGUST 25, 2021

    Sometimes, we might be presented with data in the form of ranges (in a string). The user will have to figure out a way to split this range and extract every number within that given range. Such questions are asked in coding interviews, which might not be the entire question, but a part of the bigger problem.

    In this post, we will look at two different ways of extracting numbers within the given range and put it in a list for ease of access.

    Sample input: "3, 4-5, 7-11, 11"

    Sample output: [3, 4, 5, 7, 8, 9, 10, 11, 11]

    1. Using enumerate, sum, split function and list comprehension

    The given range is enumerated over and converted into integers. Next, the hyphen symbol (-) is looked for and the integers are split based on this symbol. For our example, we have used hyphen, you can use any custom symbol, although hyphen is the most popular one when it comes to defining a number range.

    Time for an example:

    Note: This doesn't work for negative numbers since the separator used here is the hyphen symbol (-).

    2. Using map function, split function and lambda

    The map function is used to map every number in the list of strings to an integer data type. These integers are split based on the hyphen symbol (-). This is wrapped inside the lambda function to be iterated over all the ranges in the string.

    Time for an example:

    Conclusion

    In this post, we understood different ways of converting a given range of string in a list into a list of integers. These kinds of simple coding questions are also asked in coding interviews to understand how the interviewee thinks. Let us know your thoughts on this post in the comment section below.

    You may also like:

    About the author:
    I love writing about Python and have more than 5 years of professional experience in Python development. I like sharing about various standard libraries in Python and other Python Modules.
    Tags:PythonPython List
    IF YOU LIKE IT, THEN SHARE IT
     

    RELATED POSTS