Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's the Python equivalent of C++'s "a = f++;", if any?

Tags:

python

syntax

In C++, two things can happen in the same line: something is incremented, and an equality is set; i.e.:

int main() {
    int a = 3;
    int f = 2;
    a = f++; // a = 2, f = 3
    return 0;
}

Can this be done in Python?

like image 857
Cisplatin Avatar asked Nov 20 '25 18:11

Cisplatin


1 Answers

Sure, by using multiple assignment targets:

a, f = f, f + 1

or by just plain incrementing f on a separate line:

a = f
f += 1

because readable trumps overly clever.

There is no ++ operator because integers in Python are immutable; you rebind the name to a new integer value instead.

like image 109
Martijn Pieters Avatar answered Nov 22 '25 08:11

Martijn Pieters



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!