Convert List to Range in Python (2 Examples)
Hi! This short tutorial will show you 2 simple ways to convert a list into a Python range.
First, here is a quick overview of this tutorial:
Let’s dive into it!
Create Sample List
We will create a sample list for this tutorial. In your Python IDE, run the code below.
the_list = [1, 2, 3, 4, 5]
As seen, the_list consists of four integers from 1 to 5.
Example 1: Transform Lists to Ranges Using Index Positions & range() Function
In this example, we will use the index positions of the items in the list and the built-in Python
range() function to convert the list into the corresponding range.
the_range = range(the_list,the_list) print(the_range) # range(1, 5) print(type(the_range)) # <class 'range'>
We took the first value in the list, which is at index position 0, and the last value in the list, which is at index position 4, and parsed both values to the
range() function. As a result, we obtained a range, as confirmed by the type() function .
Example 2: Transform Lists to Ranges Using min() & max() inside range() Function
In this next example, we will use the
max() functions inside the
range() function to form the Python range from the list the_list.
the_range = range(min(the_list), max(the_list)) print(the_range) # range(1, 5) print(type(the_range)) # <class 'range'>
min() function takes the smallest value in the list, while the
max() function takes the largest value in the list. Both values are parsed to the
range() function to return the respective range.
So, we can either use the index positions of the elements in the list or the
max() functions to convert a list into range in Python. I hope you found this helpful!
Video, Further Resources & Summary
Do you need more explanations on how to convert lists into ranges in Python? Then you should have a look at the following YouTube video of the Statistics Globe YouTube channel.
In the video, we explain how to convert lists into ranges in Python.
The YouTube video will be added soon.
Furthermore, I encourage you to check out other interesting Python list tutorials on Statistics Globe, starting with these ones:
- Check if List of Lists is Empty in Python (2 Examples)
- Access Dictionary within List in Python (Example)
- Access List Element by Index in Python (3 Examples)
- Sort List of datetime Objects in Python (Example)
- Learn Python Programming
This post has shown how to convert lists into ranges in Python. In case you have further questions, you may leave a comment below.
This page was created in collaboration with Ifeanyi Idiaye. You might check out Ifeanyi’s personal author page to read more about his academic background and the other articles he has written for the Statistics Globe website.
Statistics Globe Newsletter