Python += Operator Evaluation in Python

Perhaps, this is one of those Python snippets that appears to perform the intended operation, yet fails and raises an exception, one that is subsequently handled. Interestingly, the operation is not entirely unsuccessful. The explanation lies in how the '+=' operater is really evaluated under Python's object model and assignment semantics. Pause and think for a moment. #Python #Programming #Developers #SoftwareEngineering

  • No alternative text description for this image

data[0] += [3] raises a type error (should be a int not a list) The error and therefore the statement is nullified by the exception handler pass.

The code will print (1, 2) pass block catches this error and does nothing, allowing the code to continue, leaving the original data tuple unchange

Like
Reply

It will fail but after printing ([1,2,3],) because the data is tuple not a list ...

It's not suppose to change the tuple but it will before the error is raised Result is ([1,2,3],)

Interesting, I didn't realize a tuple could be instantiated without parentheses.

See more comments

To view or add a comment, sign in

Explore content categories