Python 3 turn range to a list

410,451

Solution 1

You can just construct a list from the range object:

my_list = list(range(1, 1001))

This is how you do it with generators in python2.x as well. Typically speaking, you probably don't need a list though since you can come by the value of my_list[i] more efficiently (i + 1), and if you just need to iterate over it, you can just fall back on range.

Also note that on python2.x, xrange is still indexable1. This means that range on python3.x also has the same property2

1print xrange(30)[12] works for python2.x

2The analogous statement to 1 in python3.x is print(range(30)[12]) and that works also.

Solution 2

In Pythons <= 3.4 you can, as others suggested, use list(range(10)) in order to make a list out of a range (In general, any iterable).

Another alternative, introduced in Python 3.5 with its unpacking generalizations, is by using * in a list literal []:

>>> r = range(10)
>>> l = [*r]
>>> print(l)
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

Though this is equivalent to list(r), it's literal syntax and the fact that no function call is involved does let it execute faster. It's also less characters, if you need to code golf :-)

Solution 3

in Python 3.x, the range() function got its own type. so in this case you must use iterator

list(range(1000))

Solution 4

The reason why Python3 lacks a function for directly getting a ranged list is because the original Python3 designer was quite novice in Python2. He only considered the use of range() function in a for loop, thus, the list should never need to be expanded. In fact, very often we do need to use the range() function to produce a list and pass into a function.

Therefore, in this case, Python3 is less convenient as compared to Python2 because:

  • In Python2, we have xrange() and range();
  • In Python3, we have range() and list(range())

Nonetheless, you can still use list expansion in this way:

[*range(N)]

Solution 5

You really shouldn't need to use the numbers 1-1000 in a list. But if for some reason you really do need these numbers, then you could do:

[i for i in range(1, 1001)]

List Comprehension in a nutshell:

The above list comprehension translates to:

nums = []
for i in range(1, 1001):
    nums.append(i)

This is just the list comprehension syntax, though from 2.x. I know that this will work in python 3, but am not sure if there is an upgraded syntax as well

Range starts inclusive of the first parameter; but ends Up To, Not Including the second Parameter (when supplied 2 parameters; if the first parameter is left off, it'll start at '0')

range(start, end+1)
[start, start+1, .., end]
Share:
410,451

Related videos on Youtube

Boathouse
Author by

Boathouse

Updated on November 10, 2020

Comments

  • Boathouse
    Boathouse over 3 years

    I'm trying to make a list with numbers 1-1000 in it. Obviously this would be annoying to write/read, so I'm attempting to make a list with a range in it. In Python 2 it seems that:

    some_list = range(1,1000)
    

    would have worked, but in Python 3 the range is similar to the xrange of Python 2?

    Can anyone provide some insight into this?

    • njzk2
      njzk2 almost 10 years
      also, some_list[i] == i+1, so you probably don't really need a list anyway.
    • SherylHohman
      SherylHohman about 7 years
      @RikPoggi. for example, one might need to supply a list for a plotting function. Sometimes a range will suffice, but a range cannot be concatenated (is immutable), so if you need to add a default starting value to all lists being plotted, that on needs to be turned into a list also.
  • Rik Poggi
    Rik Poggi almost 12 years
    Why comprehension? Just: list(range(1000))
  • Boathouse
    Boathouse almost 12 years
    Thanks! Would you mind explaining why it's i for i in... instead of simply for i in?
  • inspectorG4dget
    inspectorG4dget almost 12 years
    I haven't worked with python3. So I'm not fully certain about how it works. I know comprehensions will work, but wasn't 100% on the casting. But if casting works, then you're right and your way is more pythonic.
  • Greg Hewgill
    Greg Hewgill almost 12 years
    @inspectorG4dget: It's not "casting", it's calling the list() constructor with an iterable. The list() constructor knows how to create a new list when given any iterable object.
  • CosmicComputer
    CosmicComputer almost 12 years
    The way list comprehensions usually work is: [doSomethingWith(i) for i in someList], because if you aren't doing something with i (such as taking one of its fields, as in [i.someField for i in someList], or using a method), doing a list comprehension is redundant. Therefore, the syntax for list comprehensions is as you see.
  • Rik Poggi
    Rik Poggi almost 12 years
    @inspectorG4dget: list(range(1000)) will work in python3 just like list(xrange(1000)) in python2
  • Jon Clements
    Jon Clements almost 12 years
    I would say "construct" or "build" (or possibly "materialise")- as you're not "converting" (as such) a generator to a list, you're creating a new list object from a data source which happens to be a generator... (but s'pose just splitting hairs and not 100% sure what I favour anyway)
  • pepr
    pepr almost 12 years
    My +1 for "construct" as it is consistent with other OO languages. The list(arg) is understood in other languages as calling a constructor of the list class. Actually, it is also the Python case. The debates whether the object is filled during the construction (as in the C++ case) or only during the first automatically called method (as in the Python __init__() method) cannot change the basic abstract idea. My view is that the list constructor takes the iterator and fills the list with the returned values.
  • mgilson
    mgilson almost 12 years
    @pepr -- Yeah, I agree. construct is probably the best word to use. One word of caution. It is not guaranteed that __init__ is called. (from the documentation of __new__ { docs.python.org/reference/datamodel.html#object.__new__ } ) "If __new__() does not return an instance of cls, then the new instance’s __init__() method will not be invoked."
  • SherylHohman
    SherylHohman about 7 years
    range(1000) will return values [0, 1, 2, .. 999] . OP needs range(1,1001) to get a list of [1, 2, 3, .. 1000]. Updating post to reflect this.
  • user2357112
    user2357112 over 6 years
    "in this case you must use iterator"? What the heck is that supposed to mean?
  • ShadowRanger
    ShadowRanger over 6 years
    To be clear, you can still one-line it: [*range(10)] works just fine for when you don't need the range for any purpose but initializing the list. Side-note: My favorite(okay, not really) part of the unpacking generalizations is that empty sets now have a literal syntax, {*()}, or as I call it, the one-eyed monkey operator. ;-)
  • Dimitris Fasarakis Hilliard
    Dimitris Fasarakis Hilliard over 6 years
    @ShadowRanger that's how I originally thought about writing it. I decided to be a bit more verbose in order to not confuse new Python users :-)
  • subtleseeker
    subtleseeker over 5 years
    Why does it give an error in jupyter notebook and working fine in shell? Error: 'range' object is not callable
  • Zach Boyd
    Zach Boyd over 5 years
    list comprehension is more generalizable
  • ShadowRanger
    ShadowRanger almost 5 years
    The whole point is to make it less convenient to make a list, because that's usually the wrong thing to do. For 99 out of 100 use cases, making an actual list is inefficient and pointless, since range itself acts like an immutable sequence in almost every way, sometimes more efficiently to boot (e.g. containment tests for ints are O(1), vs. O(n) for lists). In Python 2, people tended to use range by default, even though xrange was almost always the better option; in Python 3, you can to explicitly opt in to the list, not get it by accident by using the wrong name.
  • Earthshaker
    Earthshaker almost 5 years
    I am using python 3.7 & tried x=list(range(1000)) but got the error TypeError: 'list' object is not callable
  • kazarey
    kazarey over 4 years
    The comment about the Python 3 designer and his expertise in Python 2 is quite bold and impertinent.
  • WestCoastProjects
    WestCoastProjects about 4 years
    @kazarey But is it true? There are a lot of things in python that are questionable along these lines
  • wjandrea
    wjandrea almost 4 years
    @Earthshaker You must have a typo, like list(range(1000))()
  • wjandrea
    wjandrea almost 4 years
    This seems to be answering a different question...?
  • wjandrea
    wjandrea almost 4 years
    How does this answer the question?
  • xuancong84
    xuancong84 almost 4 years
    Yup, it answers the question by requesting Python3 developers to change and improve Python3. But it is unlikely that they will change as they are not that elegant.
  • xarena
    xarena almost 4 years
    How could I add np.nan into this list?
  • user2357112
    user2357112 about 3 years
    @subtleseeker: It works fine in a notebook. You probably assigned something to list or range.