12

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 ?

Chucks
  • 899
  • 3
  • 13
  • 29

4 Answers4

34

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]
>>> 
ergonaut
  • 6,929
  • 1
  • 17
  • 47
  • I think that may only apply to Python2, so you might want to qualify. Cheers :) – David Zemens Nov 13 '15 at 19:01
  • wonder what is the difference between this and `l = [i for i in range(9000,9004)` – letsc Nov 13 '15 at 19:04
  • @letsc doesn't that make a list, then makes a copy of that list, then throws the first list away? – ergonaut Nov 13 '15 at 19:05
  • 1
    @letsc in python 3, range is a generator so its essentially the same as calling `list` since all that `list` does is exhause `next(iterator)` and keep on appending to a list. – R Nar Nov 13 '15 at 19:11
12

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)
Neil
  • 14,063
  • 3
  • 30
  • 51
3

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)
atymic
  • 3,093
  • 1
  • 13
  • 26
shubham
  • 56
  • 6
1

The output of range is a list:

>>> print range(9000, 9004)
[9000, 9001, 9002, 9003]
Alastair McCormack
  • 26,573
  • 8
  • 77
  • 100
  • 2
    I believe this depends on the Python version. Python2 outputs a list (`xrange` is for lazy generators), Py3 outputs a generator. – mjgpy3 Nov 13 '15 at 18:59