Convert range to a list

 

What You'll Learn: In this tutorial, you'll discover how to convert a range object into a list in Python. This is useful because lists can be easily manipulated and accessed.

Definition and Usage

To convert a given range object into a list, you can call the list() built-in function and pass the range object as an argument. The list() function returns a new list with the values from the range object.

Syntax

python
mylist = list(myrange)

Examples

  1. Convert range(start, stop) into a List:

    • In this example, we take a range object starting at 4 and progressing up to 10 (excluding 10), and convert this range object into a list.

    Example Code:

    python
    # Take a range
    myrange = range(4, 10)
    # Convert range object into a list
    mylist = list(myrange)
    print(mylist)
    

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

  2. Convert range(start, stop, step) into a List:

    • In this example, we take a range object with start=4, stop=15, and step=2, and convert this range object into a list.

    Example Code:

    python
    # Take a range
    myrange = range(4, 15, 2)
    # Convert range object into a list
    mylist = list(myrange)
    print(mylist)
    

    Output: [4, 6, 8, 10, 12, 14]
     

Try It Yourself: Fun Exercises

  1. Create a List of Numbers:
    • Use range to generate a sequence of numbers from 1 to 20 and convert it into a list.
  2. Step Up Your List:
    • Generate a list of even numbers between 2 and 30 using range(start, stop, step).

Summary:

In this Python tutorial, we learned how to convert a range object into a list using the list() built-in function. This method allows you to easily manipulate and access ranges as lists. Keep experimenting and have fun with Python!