Domanda

I was looking at some code that returns the second largest element of a list and came across a weird use of commas. Hopefully someone can explain it to me:

it is the

m1, m2 = x, m1

part of the following code:

def second_largest(numbers):
    m1, m2 = None, None

    for x in numbers:
        if x >= m1:
            m1, m2 = x, m1
        elif x > m2:
           m2 = x

    return m2

What is getting assigned what in this if statement?

È stato utile?

Soluzione

Essentially, the tuple (m1,m2) is recieving the values in the tuple (x,m1). After the statement m1 will have the old value of x and m2 will have the old value of m1. Example:

>>> x = 2
>>> y = 3
>>> z = 4
>>> x,y = y,z
>>> x
3
>>> y
4

The tuple (x,m1) is created before any assignments are made. As a result, this syntax is often used for swapping two variables. For example, x,y = y,x will swap the values in x and y.

Altri suggerimenti

This code: m1, m2 = x, m1 means storing the value of x to m1, and value of m1 to m2.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top