简体   繁体   中英

Python - don't understand operator - exponent

I'm going through the Python Institute's tutorial, and they have an expression in a for loop, which taking a list of 1,2,3... produces output of 1,4,9,16. So, it appears to me, it's squaring each element.

elem **= 2

I don't understand what the "=" is doing there. Shouldn't it be written elem ** 2? Is it just an alternative way to write it?

It appears to work in code.

def listUpdater(lst):
updList = []
for elem in lst:
    elem **= 2
    updList.append(elem)
return updList


def main():
    l = [1, 2, 3, 4, 5]
    print(listUpdater(l))

In this link you have a nice overview of Python operators with an alternative way to write them too.

Essentially the combination of an operator like ** with a = means that first the operator ist executed and the result of that is assigned to the variable on the left side.

So in your case elem is squared and the result is saved in the same elem and in the next line appended to updList .

An alternative way of writing it would be elem = elem ** 2 .

The '=' is applying the changes to the variable 'elem', without the '=', it will give you the square of it, but the variable will not change, it will stay not squared.

The '=' sign changes the elem variable.

Instead of writing:

elem = elem**2

You can instead write:

elem **= 2

The **= operator applies the operation of power with the arguments from both sides of the operator and saves it to the variable. This is the same as doing elem = elem ** 2 .

Similarly, if you wanted to increment a variable by 1, you could do i+=1 . The value of i would be incremented.

Basically you could write elem **2 It will work fine. you could add this line print(elem **@2) and see its working. The reason to add "=" sign is to resign the value that you have computed by elem**2 into elem.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM