Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What does *= mean in python? [duplicate]

Tags:

python

For example in this code:

def product(list):
    p =1
    for i in list:
        p *= i
    return p

I found this code, but I need to be able to explain each and every part of it.

like image 902
Simon Önnered Avatar asked Oct 21 '13 11:10

Simon Önnered


2 Answers

It's shorthand for

p = p * i

It's analogous to the more frequently encountered p += i

like image 153
Brian Agnew Avatar answered Sep 28 '22 10:09

Brian Agnew


Taken from the first result in google:

Multiply AND assignment operator, It multiplies right operand with the left operand and assign the result to left operand

*= is the same as saying p = p * i.

This link contains a list of all the operators in their various, wonderful combinations.

Example

A pseudo-code explanation of your code is as follows:

assume list := {4, 6, 5, 3, 5, 1}
p := 1.

for(each number in list)
    p = the current value of p * the current number.
    // So: 1 * 4, 4 * 6, 24 * 5, 120 * 3...

return p. 
like image 33
christopher Avatar answered Sep 28 '22 10:09

christopher