Given two numbers r1 and r2 (which defines the range), write a Python program to create a list with the given range (inclusive).
Input : r1 = -1, r2 = 1 Output : [-1, 0, 1] Input : r1 = 5, r2 = 9 Output : [5, 6, 7, 8, 9]
Let’s discuss a few approaches to do this task.
Approach #1 : Naive Approach
A naive method to create list within a given range is to first create an empty list and append successor of each integer in every iteration of for loop.
[-1, 0, 1]
Approach #2 : List comprehension
We can also use list comprehension for the purpose. Just iterate ‘item’ in a for loop from r1 to r2 and return all ‘item’ as list. This will be a simple one liner code.
[-1, 0, 1]
Approach #3 : using Python
Python comes with a direct function
range() which creates a sequence of numbers from start to stop values and print each item in the sequence. We use
range() with r1 and r2 and then convert the sequence into list.
[-1, 0, 1]
Approach #4 : Using
Python numpy.arange() returns a list with evenly spaced elements as per the interval. Here we set the interval as 1 according to our need to get the desired output.
[-1 0 1]
Attention geek! Strengthen your foundations with the Python Programming Foundation Course and learn the basics.
To begin with, your interview preparations Enhance your Data Structures concepts with the Python DS Course.
- Python program to create a list of tuples from given list having number and its cube in each tuple
- Python | Numbers in a list within a given range
- Python | Generate random numbers within a given range and store in a list
- Python | Find missing numbers in a sorted list range
- Python | Ways to create triplets from given list
- Python - Create Nested Dictionary using given List
- wxPython - Create Radio Button using Create() function
- wxPython - Create Static Box using Create() method
- Python List Comprehension | Three way partitioning of an array around a given range
- Python program to extract characters in given range from a string list
- Python - Test for all Even elements in the List for the given Range
- Python | Convert list of string to list of list
- Python | Convert list of tuples to list of list
- Python | Convert List of String List to String List
- Python | Create a dictionary using list with none values
- Python program to create a list centered on zero
- How to create a list of object in Python class
- Create a tuple from string and list - Python
- Use get() method to create a dictionary in Python from a list of elements
- Python - Create dictionary from the 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 firstname.lastname@example.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.
Improved By : ManasChhabra2