Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python - Create list with numbers between 2 values?

Tags:

python

list

How would I create a list with values between two values I put in? For example, the following list is generated for values from 11 to 16:

list = [11, 12, 13, 14, 15, 16] 
like image 608
lorde Avatar asked Aug 16 '13 04:08

lorde


People also ask

How do I make a list between two numbers in Python?

Use the range() Function to Create a List of Numbers From 1 to N. The range() function is very commonly used in Python. It returns a sequence between two numbers given in the function arguments. The starting number is 0 by default if not specified.

How do you define a list of numbers in Python?

In Python, a list is created by placing elements inside square brackets [] , separated by commas. A list can have any number of items and they may be of different types (integer, float, string, etc.).


2 Answers

Use range. In Python 2.x it returns a list so all you need is:

>>> range(11, 17) [11, 12, 13, 14, 15, 16] 

In Python 3.x range is a iterator. So, you need to convert it to a list:

>>> list(range(11, 17)) [11, 12, 13, 14, 15, 16] 

Note: The second number is exclusive. So, here it needs to be 16+1 = 17

EDIT:

To respond to the question about incrementing by 0.5, the easiest option would probably be to use numpy's arange() and .tolist():

>>> import numpy as np >>> np.arange(11, 17, 0.5).tolist()  [11.0, 11.5, 12.0, 12.5, 13.0, 13.5,  14.0, 14.5, 15.0, 15.5, 16.0, 16.5] 
like image 65
Jared Avatar answered Sep 24 '22 06:09

Jared


You seem to be looking for range():

>>> x1=11 >>> x2=16 >>> range(x1, x2+1) [11, 12, 13, 14, 15, 16] >>> list1 = range(x1, x2+1) >>> list1 [11, 12, 13, 14, 15, 16] 

For incrementing by 0.5 instead of 1, say:

>>> list2 = [x*0.5 for x in range(2*x1, 2*x2+1)] >>> list2 [11.0, 11.5, 12.0, 12.5, 13.0, 13.5, 14.0, 14.5, 15.0, 15.5, 16.0] 
like image 41
devnull Avatar answered Sep 22 '22 06:09

devnull