0

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?

5
  • 1
    x is getting assigned to m1 and m1 to m2, in unison. Commented Jul 23, 2013 at 18:26
  • This is poor coding for the exact reason why it wasn't entirely clear to you what was happening here at first glance. Although it's a line saver, it's less apparent what you're trying to do and makes your code harder to read. Commented Jul 23, 2013 at 18:29
  • I'd say what makes it hard to read is the variable names m1 and m2. The multiple assignment is standard Python. Commented Jul 23, 2013 at 18:39
  • Also, comparing numbers to None is a really bad idea. Commented Jul 23, 2013 at 18:40
  • Multiple assignments are standard in python, I agree, but not like that, more like x, y, z = some_tuple. If you're setting two variables to two other variables I was taught it's improper to try to squish it all into one line Commented Jul 23, 2013 at 19:01

2 Answers 2

3

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.

Sign up to request clarification or add additional context in comments.

Comments

2

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.