Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python range to list

Tags:

python

I am trying to convert a range to list.

nums = []
for x in range (9000, 9004):
    nums.append(x)
    print nums

output

[9000]
[9000, 9001]
[9000, 9001, 9002]
[9000, 9001, 9002, 9003]

I just need something like

 [9000, 9001, 9002, 9003]

How do I get just the requred list ?

like image 465
Chucks Avatar asked Nov 13 '15 18:11

Chucks


4 Answers

Python 3

For efficiency reasons, Python no longer creates a list when you use range. The new range is like xrange from Python 2.7. It creates an iterable range object that you can loop over or access using [index].

If we combine this with the positional-expansion operator *, we can easily generate lists despite the new implementation.

[*range(9000,9004)]

Python 2

In Python 2, range does create a list... so:

range(9000,9004)
like image 110
Neil Avatar answered Sep 18 '22 16:09

Neil


You can just assign the range to a variable:

range(10)
>>> [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

In your case:

>>> nums = range(9000,9004)
>>> nums
[9000, 9001, 9002, 9003]
>>> 

However, in python3 you need to qualify it with a list()

>>> nums = list(range(9000,9004))
>>> nums
[9000, 9001, 9002, 9003]
>>> 
like image 41
ergonaut Avatar answered Sep 17 '22 16:09

ergonaut


Since you are taking the print statement under the for loop, so just placed the print statement out of the loop.

nums = []
for x in range (9000, 9004):
    nums.append(x)
print (nums)
like image 22
shubham Avatar answered Sep 18 '22 16:09

shubham


The output of range is a list:

>>> print range(9000, 9004)
[9000, 9001, 9002, 9003]
like image 34
Alastair McCormack Avatar answered Sep 20 '22 16:09

Alastair McCormack