The Python data model doesn't really have variables like other languages. It has objects which may be bound to names. So a Python "variable" isn't a memory location like it is in many other languages, it's simply a label on an object. An object may have multiple names, or it may have none. See Facts and myths about Python names and values by SO veteran Ned Batchelder for further information on this topic.
Python integers are immutable objects, so you can't actually increment them. Of course, you can create a new integer object that has a value 1 greater than the object currently named a
and bind the name a
to that new object.
So what you're asking to do isn't exactly a natural operation in Python. However, you can get close. As others have mentioned, you can sort-of do it by placing a
into a mutable container object. Eg,
def inc(lst):
lst[0] += 1
a = 7
b = [a]
inc(b)
print b, a
output
[8] 7
A somewhat more satisfactory approach is to refer to the name via the global()
dictionary:
def inc(k):
globals()[k] += 1
a = 7
inc('a')
print a
output
8
However, modifying things via globals()
is generally frowned upon, and it's useless if you want to modify a name that's local to a function.
Another option is to define a custom class:
class MutInt(object):
def __init__(self, v):
self.v = v
def __str__(self):
return str(self.v)
def inc(self):
self.v += 1
a = MutInt(7)
print a
a.inc()
print a
output
7
8
But that's still rather ugly (IMHO), and you'd have to define all the methods of int
in it to make the class useful.