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?

miken32
  • 42,008
  • 16
  • 111
  • 154
natsuki_2002
  • 24,239
  • 21
  • 46
  • 50
  • 1
    `x` is getting assigned to `m1` and `m1` to `m2`, in unison. – voithos Jul 23 '13 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. – scohe001 Jul 23 '13 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. – user2357112 Jul 23 '13 at 18:39
  • Also, comparing numbers to `None` is a really bad idea. – user2357112 Jul 23 '13 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 – scohe001 Jul 23 '13 at 19:01

2 Answers2

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.

Blair
  • 6,623
  • 1
  • 36
  • 42
2

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

jh314
  • 27,144
  • 16
  • 62
  • 82