range() to a list in Python
Often times we want to create a list containing a continuous value like, in a range of 100-200. Let’s discuss how to create a list using the range() function.
Will this work ?
# Create a list in a range of 10-20 My_list = [range(10, 20, 1)] # Print the list print(My_list) |
Output :

As we can see in the output, the result is not exactly what we were expecting because Python does not unpack the result of the range() function.
Code #1: We can use argument-unpacking operator i.e. *.
# Create a list in a range of 10-20 My_list = [*range(10, 21, 1)] # Print the list print(My_list) |
Output :

As we can see in the output, the argument-unpacking operator has successfully unpacked the result of the range function.
Code #2 : We can use the extend() function to unpack the result of range function.
# Create an empty list My_list = [] # Value to begin and end with start, end = 10, 20 # Check if start value is smaller than end value if start < end: # unpack the result My_list.extend(range(start, end)) # Append the last value My_list.append(end) # Print the list print(My_list) |
Output :

Recommended Posts:
- Python | Numbers in a list within a given range
- Python | Print list elements in circular range
- Python List Comprehension | Three way partitioning of an array around a given range
- Python | Generate random numbers within a given range and store in a list
- Python | Convert list of string to list of list
- Python program to create a list of tuples from given list having number and its cube in each tuple
- Python | Convert list of string into sorted list of integer
- Python | Find maximum length sub-list in a nested list
- Python | Maximum sum of elements of list in a list of lists
- Python | Remove all values from a list present in other list
- Python | Ways to sum list of lists and return sum list
- Python | Convert a string representation of list into list
- Python List Comprehension | Segregate 0's and 1's in an array list
- Python | Convert a nested list into a flat list
- Python | Sort the values of first list using second list
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.



