Domanda

I'm a begginer in Python, and I was reading a book.

So this is a funcion that imitates range()

def interval(start, stop=None, step=1):
    'Imitates range() for step > 0'
    if stop is None: 
        start, stop = 0, start      # How is this evaluated?
    result = []
    i = start 
    while i < stop:
        result.append(i)
        i += step
    return result

My question here is: How is evaluated the:

start, stop = 0, start part?

Because I understand that the parameters should evaluate like this:

5, stop = 0, 5 (I know I'm wrong but I need you to tell me how is this part evaluated)

È stato utile?

Soluzione

The form

x, y = a, b

is a multiple assignment which is well (but obtusely) documented. The simple example I gave would be equivalent to

x = a
y = b

or in the case of your example start, stop = 0, start

stop = start
start = 0

Notice how I reordered the assignments; this is one advantage of multiple assignment. In this case you'd have to add a temporary variable if you wanted the same effect:

temp = start
start = 0
stop = temp 

Altri suggerimenti

If you call interval( 10 ), then start = 0 and stop = 10. When interval( 5, 10 ) is called, then start = 5 and stop = 10.

start, stop = 0, start is equivalent to stop = start; start = 0.

a, b = c, d is equivalent to a = c and b = d

This is called tuple unpacking.

In [24]: x,y = 0,1

In [25]: print(x)
0

In [26]: print(y)
1

You can do this for any sequence. In the above, you are in-line specifying a tuple with (0,1). You can also unpack, say, an iterable:

In [28]: a,b,c = range(3)

In [29]: a
Out[29]: 0

In [30]: b
Out[30]: 1

In [31]: c
Out[31]: 2

but you have to make sure that the number of arguments you provide to unpack makes sense.

In [32]: a,b = range(3)
---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
/home/ben/<ipython-input-32-ec703b8346af> in <module>()
----> 1 a,b = range(3)

ValueError: too many values to unpack (expected 2)

In [33]: a,b,c,d = range(3)
---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
/home/ben/<ipython-input-33-16ef42f82877> in <module>()
----> 1 a,b,c,d = range(3)

ValueError: need more than 3 values to unpack

Note that (and this is the part that seems to be confusing you) the right side is evaluated before the left side. This allows for the common idiom:

In [34]: x = 0

In [35]: y = 1

In [36]: x,y = y,x 
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top