i++ in Python?

Ian Bicking ianb at colorstudy.com
Thu Jul 18 18:44:56 EDT 2002


On Thu, 2002-07-18 at 17:29, OtisUsenet wrote:
> Python newbie question.  How does one do something like this in
> Python:
> 
>     # assign the value of j to i and then increment j by 1
>     i = j++

I'm sure a lot of people are going to pile onto this one, but the
answers might go something like this...

short answer (conventional way of doing it):
i = j
j += 1

clever answer:
i, j = j, j+1

medium answer:
Assignment is a statement (by design), so you can't reassign j inside an
expression.

longer answer:
Unlike C, Python variables are bindings.  So, assuming j starts out as
1, j doesn't *contain* 1 -- it *points to* 1.  So when you do:

j += 1

You are rebinding (repointing) j to 2.  In C, j is actually a place in
memory, and when you increment j you're taking that piece of memory and
changing it.  Incrementing in Python doesn't really happen like that.

--
Ian Bicking           Colorstudy Web Development
ianb at colorstudy.com   http://www.colorstudy.com
4869 N Talman Ave, Chicago, IL 60625 / (773) 275-7241







More information about the Python-list mailing list