1

I am finding problems in when I should use *= or be explicit in using my code. I'm trying to do simple integer multiplication and addition in Python. So to take a number, multiply it by 3 and add 1. Is there a specific situation where I should use:

number *= 3 number += 1 

Or

number = (number * 3) + 1 

Is there a difference between the two, or is this a matter of personal preference?

2
  • 1
    What looks clearer to you? Commented Feb 21, 2018 at 10:32
  • There is no difference other than how it looks, assuming number is an integer or a float. Commented Feb 21, 2018 at 12:16

1 Answer 1

4

For simple values like integers, it won't usually make any difference and is a matter of style. For other objects it may make a difference, since + will invoke the __add__ method and += will invoke the __iadd__ method if present, which updates the object itself. Simple example that comes to mind (here demonstrating __ior__):

foo = set('foo') bar = foo bar = bar | set('bar') # vs bar |= set('bar') 

In this case the difference between | and |= is that the latter also modifies foo, while | does not.

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.