Behaviour of increment and decrement operators in Python

0 votes

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++?

Jul 26, 2018 in Python by bug_seeker
• 15,520 points
3,563 views

1 answer to this question.

0 votes

When you want to increment or decrement, you typically want to do that on an integer. Like so:

b++

But in Python, integers are immutable. That is you can't change them. This is because the integer objects can be used under several names.

So you have to reassign. Like this:

b = b + 1

Or simpler:

b += 1

Which will reassign b to b+1. That is not an increment operator, because it does not increment b, it reassigns it.

In short: Python behaves differently here, because it is not C, and is not a low level wrapper around machine code, but a high-level dynamic language, where increments don't make sense, and also are not as necessary as in C, where you use them every time you have a loop.

answered Jul 26, 2018 by Priyaj
• 58,090 points

Related Questions In Python

0 votes
1 answer

Can someone explain the behaviour of increment and decrement operators in python

down voteaccepted ++ is not an operator. It is ...READ MORE

answered May 15, 2018 in Python by aryya
• 7,450 points
1,508 views
0 votes
1 answer

How can I find out the index of an element from row and column in Python?

You probably want to use np.ravel_multi_index: [code] import numpy ...READ MORE

answered Apr 16, 2018 in Python by charlie_brown
• 7,720 points
2,033 views
0 votes
1 answer

what are "and" and "or" operators in Python?

AND - True if both the operands ...READ MORE

answered Apr 18, 2018 in Python by Johnathon
• 9,090 points
650 views
0 votes
1 answer

Increment operators in Python

Python has no unary operators. So use ...READ MORE

answered May 12, 2018 in Python by Hamartia's Mask
• 1,580 points
805 views
0 votes
2 answers
+1 vote
2 answers

how can i count the items in a list?

Syntax :            list. count(value) Code: colors = ['red', 'green', ...READ MORE

answered Jul 7, 2019 in Python by Neha
• 330 points

edited Jul 8, 2019 by Kalgi 4,051 views
0 votes
1 answer
0 votes
2 answers

What are the types of dictionary in python?

There are 4 types of dictionary Empty Integer Mixed Dictionary with ...READ MORE

answered Feb 14, 2019 in Python by Shashank
• 1,370 points
696 views
0 votes
1 answer

*args and **kwargs in python

In cases when we don’t know how ...READ MORE

answered Jul 20, 2018 in Python by Priyaj
• 58,090 points
632 views
webinar REGISTER FOR FREE WEBINAR X
REGISTER NOW
webinar_success Thank you for registering Join Edureka Meetup community for 100+ Free Webinars each month JOIN MEETUP GROUP