Python program to create a list centered on zero
Given two integer variables, limit and diff, write a Python program to create a list that is centered on zero, using limit, which specifies limit of the list and diff that specifies the common difference between integers.
Examples:
Input : limit = 1, diff = 0.5 Output : [-1, -0.5, 0.0, 0.5, 1] Input : limit = 25, diff = 5 Output : [-25, -20, -15, -10, -5, 0, 5, 10, 15, 20, 25]
Approach #1 : Naive Approach
This is a naive approach to the above problem. First, create an empty list ‘lst’, and then we use a while loop to append the next integer with a difference equal to ‘diff’.
# Python3 program to Convert a # list to dictionary def create(limit, diff): lst = [-limit] while lst[-1] < limit: lst.append(lst[-1] + diff) lst[-1] = limit return lst # Driver code limit = 1diff = 0.5print(create(limit, diff)) |
Output:
[-1, -0.5, 0.0, 0.5, 1]
Approach #2 : Using Python Numpy
Using Numpy module makes the solution a lot easier. In this method, we use np.arange which return evenly spaced values within a given interval ‘diff’.
# Python3 program to Convert a # list to dictionary import numpy as np def create(limit, diff): lst = np.arange(diff, limit, diff) if (lst[-1] != limit): lst = np.r_[lst, limit] return np.r_[-lst[::-1], 0, lst].tolist() # Driver code limit = 1diff = 0.5print(create(limit, diff)) |
Output:
[-1, -0.5, 0.0, 0.5, 1]
Recommended Posts:
- Python program to create a list of tuples from given list having number and its cube in each tuple
- Python | Ways to create triplets from given list
- Python | Create a dictionary using list with none values
- Python | Create list of numbers with given range
- How to create a list of object in Python class
- Python program to create a dictionary from a string
- Program to create grade calculator in Python
- Python program to create Bankaccount class with deposit, withdraw function
- Python program to right rotate a list by n
- Python program to convert a list to string
- Python program to find sum of elements in list
- Python Program to Reverse a linked list
- Python | Program to convert String to a List
- Python program to swap two elements in a list
- Python program to interchange first and last elements in a 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.



