Assign a range to a variable (Python)

后端 未结 3 987
醉酒成梦
醉酒成梦 2021-01-12 16:00

Whenever I try to assign a range to a variable like so:

Var1 = range(10, 50)

Then try to print the variable:

Var1 = range(1         


        
相关标签:
3条回答
  • 2021-01-12 16:31

    Thats because range returns a range object in Python 3. Put it in list to make it do what you want:

    >>> Var1 = range(10, 50)
    >>> print(list(Var1))
    [10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31,  
    32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49]
    >>>
    
    0 讨论(0)
  • 2021-01-12 16:36

    This is something that was changed in Python 3.0. You could recreate a similar function in Python 2.7 like so,

    def range(low, high=None):
      if high == None:
        low, high = 0, low
      i = low
      while i < high:
        yield i
        i += 1
    

    The benefit of this, is that the list doesn't have to be created before its used.

    for i in range(1,999999):
      text = raw_input("{}: ".format(i))
      print "You said {}".format(text)
    

    Which works like this:

    1: something
    You said something
    2: something else
    You said something else
    3: another thing
    You said another thing
    

    In Python 3.X, if we never get to the end of our loop (999997 iterations), it will never calculate all of the items. In Python 2.7 it has to build the entire range initially. In some older Python implementations, this was very slow.

    0 讨论(0)
  • 2021-01-12 16:47

    You should probably understand a bit of what is happening under the hood.

    In python 3, range returns a range object, not a list like you may have been expecting. (n.b. python 3's range is python 2's xrange)

    #python 2
    >>> type(range(5))
    <type 'list'>
    
    #python 3
    >>> type(range(5))
    <class 'range'>
    

    What does that mean? Well, the range object is simply an iterator - you need to force it to iterate to get its contents. That may sound annoying to the neonate, but it turns out to be quite useful.

    >>> import sys
    >>> sys.getsizeof(range(5))
    24
    >>> sys.getsizeof(range(1000000))
    24
    

    The biggest advantage of doing things this way: constant (tiny) memory footprint. For this reason, many things in the standard library simply return iterators. The tradeoff is that if you simply want to see the iterated range, you have to force it to iterate. The most common idiom to do that is list(range(n)). There's also comprehensions, for loops, and more esoteric methods. Iterators are a huge part of learning python so get used to them!

    0 讨论(0)
提交回复
热议问题