1

Is it legal to do

a = b = 3

in python? If so, is it a bad practice?

7
  • 5
    You could have tried that out in under 1 second. Commented Jun 26, 2013 at 8:02
  • 1
    @MartijnPieters, but I can't try the second question out. Commented Jun 26, 2013 at 8:03
  • IT IS NOT A GOOD PRACTICE Commented Jun 26, 2013 at 8:04
  • 3
    @Shai YES IT IS GOOD PRACTICE Commented Jun 26, 2013 at 8:33
  • 2
    Also this question isn't primarily opinion based, this is a feature of Python that should most definitely be promoted, nobody can argue against this Commented Jun 26, 2013 at 8:34

2 Answers 2

8

Yes, it is legal to do so. No, it is not bad practice.

Just take into account that the right-hand side, the value expression, is evaluated first, and assignment then takes place from left to right; 3 is assigned to a first, then to b.

From the assignment statement documentation:

An assignment statement evaluates the expression list (remember that this can be a single expression or a comma-separated list, the latter yielding a tuple) and assigns the single resulting object to each of the target lists, from left to right.

You assign the same value to all targets. That means that each variable refers to one value only. This is important when that value is mutable, like a list or a dictionary.

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

5 Comments

PEP-8 advices against multiple expressions on a single line. Is this not an instance of such?
No, this is not. It is one statement (PEP 8 warns against multiple statements, not multiple expressions). PEP 8 is otherwise silent on the number of targets in an assignment.
@Vorac Where on the PEP-8? I can't seem to find it myself
@Haidro: Compound statements (multiple statements on the same line) are generally discouraged., referring to using if something: true_statement on one line, or using ; to put multiple statements on one line.
@MartijnPieters, lightning fast! I know where it is and shill you got it first. Do you search very quickly or do you just know it all by hearth :D?
8

Yes, just watch out for stuff like this:

a = b = []
a.append(2)
print a
print b

Prints:

[2]
[2]

But other than that, it's fine. @Martijn has a lot of information in his answer, so check it out :).

1 Comment

@kawing-chiu Only half an hour? Would have taken me hours to figure out

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.