Assign a range to a variable (Python)

后端 未结 3 1096
醉酒成梦
醉酒成梦 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: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))
    
    
    #python 3
    >>> type(range(5))
    
    

    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!

提交回复
热议问题