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
mylist = list(myrange)
Examples
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]
Convert
range(start, stop, step)into a List:- In this example, we take a range object with
start=4,stop=15, andstep=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]
- In this example, we take a range object with
Try It Yourself: Fun Exercises
- Create a List of Numbers:
- Use
rangeto generate a sequence of numbers from 1 to 20 and convert it into a list.
- Use
- Step Up Your List:
- Generate a list of even numbers between 2 and 30 using
range(start, stop, step).
- Generate a list of even numbers between 2 and 30 using
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!