Skip to content
Fix Code Error

Behaviour of increment and decrement operators in Python

March 13, 2021 by Code Error
Posted By: Anonymous

I notice that a pre-increment/decrement operator can be applied on a variable (like ++count). It compiles, but it does not actually change the value of the variable!

What is the behavior of the pre-increment/decrement operators (++/–) in Python?

Why does Python deviate from the behavior of these operators seen in C/C++?

Solution

++ is not an operator. It is two + operators. The + operator is the identity operator, which does nothing. (Clarification: the + and - unary operators only work on numbers, but I presume that you wouldn’t expect a hypothetical ++ operator to work on strings.)

++count

Parses as

+(+count)

Which translates to

count

You have to use the slightly longer += operator to do what you want to do:

count += 1

I suspect the ++ and -- operators were left out for consistency and simplicity. I don’t know the exact argument Guido van Rossum gave for the decision, but I can imagine a few arguments:

  • Simpler parsing. Technically, parsing ++count is ambiguous, as it could be +, +, count (two unary + operators) just as easily as it could be ++, count (one unary ++ operator). It’s not a significant syntactic ambiguity, but it does exist.
  • Simpler language. ++ is nothing more than a synonym for += 1. It was a shorthand invented because C compilers were stupid and didn’t know how to optimize a += 1 into the inc instruction most computers have. In this day of optimizing compilers and bytecode interpreted languages, adding operators to a language to allow programmers to optimize their code is usually frowned upon, especially in a language like Python that is designed to be consistent and readable.
  • Confusing side-effects. One common newbie error in languages with ++ operators is mixing up the differences (both in precedence and in return value) between the pre- and post-increment/decrement operators, and Python likes to eliminate language “gotcha”-s. The precedence issues of pre-/post-increment in C are pretty hairy, and incredibly easy to mess up.
Answered By: Anonymous

Related Articles

  • Reference — What does this symbol mean in PHP?
  • What does this symbol mean in JavaScript?
  • Form field border-radius is not working only on the…
  • Can a "User Assigned Managed Identity" be used locally?
  • OpenIddict Roles/Policy returns 403 Forbidden
  • How can I pass a wct test while rearranging children…
  • How should a model be structured in MVC?
  • Increment and decrement counter JS
  • C# group by a list contains another class
  • Circular Dependency with two depending Services
  • Count with CSS Animation: Animate only once instead…
  • What are the undocumented features and limitations…
  • Ukkonen's suffix tree algorithm in plain English
  • Why does C++ code for testing the Collatz conjecture…
  • What is a NullReferenceException, and how do I fix it?
  • AngularJS ui-router login authentication
  • What's the difference between eval, exec, and compile?
  • How does PHP 'foreach' actually work?
  • Finding all possible combinations of numbers to…
  • Reduce vs Collect method on Parallel Streams vs…
  • What is the difference between Scope_Identity(),…
  • What are all the user accounts for IIS/ASP.NET and…
  • Smart way to truncate long strings
  • COUNT(*) vs. COUNT(1) vs. COUNT(pk): which is better?
  • increment operator vs. i + 1 in loop
  • How to print an AST from a parser generator to graphviz?
  • ASP.NET MVC 5 - Identity. How to get current ApplicationUser
  • How to generate a random string of a fixed length in Go?
  • C compile error: Id returned 1 exit status
  • JavaScript gives NaN error on the page but variable…
  • mongodb group values by multiple fields
  • How to get rid of this problem ( On adding a nuget…
  • An explicit value for the identity column in table…
  • Can't install via pip because of egg_info error
  • How do SO_REUSEADDR and SO_REUSEPORT differ?
  • Bad operand type for unary +: 'str'
  • Callback functions in C++
  • Meaning of "[: too many arguments" error from if []…
  • Sorting 1 million 8-decimal-digit numbers with 1 MB of RAM
  • How do I merge two dictionaries in a single…
  • dart-polymer update polymer dom elements
  • How to prevent scrolling the whole page?
  • "Notice: Undefined variable", "Notice: Undefined…
  • Getting the closest string match
  • How to update Identity Column in SQL Server?
  • Equals(=) vs. LIKE
  • Why does ++[[]][+[]]+[+[]] return the string "10"?
  • Replacing a 32-bit loop counter with 64-bit…
  • How to filter a RecyclerView with a SearchView
  • What is an optional value in Swift?
  • JWT authentication for ASP.NET Web API
  • Adding an identity to an existing column
  • What is a plain English explanation of "Big O" notation?
  • How to test a global event bus in VueJS
  • What does "Fatal error: Unexpectedly found nil while…
  • Apache server keeps crashing, "caught SIGTERM,…
  • Usage of __slots__?
  • Firebase cloud function onUpdate is triggered but…
  • How to format a phone number in a textfield
  • Easy interview question got harder: given numbers…
  • How to convert an XML file to nice pandas dataframe?
  • Design DFA accepting binary strings divisible by a…
  • Best way to get identity of inserted row?
  • Memcached vs. Redis?
  • R: "Unary operator error" from multiline ggplot2 command
  • Best way to communicate between instances of the…
  • How to implement an STL-style iterator and avoid…
  • Can you "compile" PHP code and upload a binary-ish…
  • Manage Identity Custom Identity Name
  • Vue: the template root disallows v-for directives
  • How to generate a random number in C++?
  • MVC 5 Access Claims Identity User Data
  • Vue.js - click events and "this"
  • Get the second largest number in a list in linear time
  • How to compare std::vector items with key elements…
  • Elegant ways to support equivalence ("equality") in…
  • How to solve Internal Server Error in Next.Js?
  • Share data across different components in Vuejs
  • How to load aurelia-validation plugin in Karma test…
  • How can you force the UI to update in the middle of…
  • Fastest way to iterate over all the chars in a String
  • CSS selector for first element with class
  • Remove leading zeros from a number in Javascript
  • How can I get the Amazon Cognito Identity SDK…
  • What is the copy-and-swap idiom?
  • Validate that a string is a positive integer
  • Best practices for circular shift (rotate) operations in C++
  • How to update other fields based on a field value in…
  • How to delete an element from an array in C#
  • Why do we use __init__ in Python classes?
  • Vuex mapState reference error when vuex.js is…
  • ASP.NET Identity - HttpContext has no extension…
  • What are bitwise shift (bit-shift) operators and how…
  • Reset identity seed after deleting records in SQL Server
  • Change column type in pandas
  • How can I manually compile a svelte component down…
  • How to use React Test Utilities with Jasmine
  • what is the use of annotations @Id and…
  • Validation failed for one or more entities. See…
  • Explanation on Integer.MAX_VALUE and…

Disclaimer: This content is shared under creative common license cc-by-sa 3.0. It is generated from StackExchange Website Network.

Post navigation

Previous Post:

Define a global variable in a JavaScript function

Next Post:

$(document).ready equivalent without jQuery

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

.net ajax android angular arrays aurelia backbone.js bash c++ css dataframe ember-data ember.js excel git html ios java javascript jquery json laravel linux list mysql next.js node.js pandas php polymer polymer-1.0 python python-3.x r reactjs regex sql sql-server string svelte typescript vue-component vue.js vuejs2 vuetify.js

  • you shouldn’t need to use z-index
  • No column in target database, but getting “The schema update is terminating because data loss might occur”
  • Angular – expected call-signature: ‘changePassword’ to have a typedeftslint(typedef)
  • trying to implement NativeAdFactory imports deprecated method by default in flutter java project
  • What should I use to get an attribute out of my foreign table in Laravel?
© 2022 Fix Code Error