Convert range to a list

Converting a Range into a List: The Basics

What You'll Learn: In this tutorial, you'll discover how to convert a range object into a list in Python using the built-in list() function. This is a handy way to work with sequences of numbers in a more flexible format.

Syntax

To convert a range object myrange into a list mylist, you can use the following syntax:

python
mylist = list(myrange)

Examples

  1. Convert range(start, stop) into a List
    • Description: In this example, we take a range object starting at 4 and progressing up to 10 (excluding 10), and convert it 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
    • Description: In this example, we take a range object with start=4, stop=15, and step=2, and convert it 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 Range:
    • Define a range object with different start, stop, and step values, and convert it into a list.
  2. Experiment with Steps:
    • Experiment with different step values to see how it affects the output list.

Summary:

In this tutorial on Python Ranges, we learned how to convert a range object into a list using the list() built-in function. This simple technique helps you work with sequences of numbers more flexibly. Keep experimenting and have fun with Python!