Ryan_Liu
Ryan_Liu

Reputation: 279

In python,what does ++ mean?

I read a script like that

for ... :
   for ...:
      ++i

but what does ++ mean? Is ++ operator is python?

Upvotes: 0

Views: 3773

Answers (4)

georg
georg

Reputation: 214949

Python is an implicitly typed language, therefore, unless we know what type the variable has, we cannot tell for sure what happens if we apply an operator to it. In your example, i is not necessarily an integer, it can be an object with an overloaded unary + (__pos__), for example:

class Duplicator(object):
    def __init__(self, s):
        self.s = s

    def __pos__(self):
        self.s += self.s
        return self

    def __str__(self):
        return self.s

z = Duplicator("ha ")
# 1000 lines of code
print +z
print ++z
print +++z

So the answer to your question "what does ++x mean in python" is "it depends on what x is".

Upvotes: 3

Ahmet DAL
Ahmet DAL

Reputation: 4682

You can use i+=1 instead of i++ for your for loop. There is no ++ usage in Python.

Upvotes: 3

jamylak
jamylak

Reputation: 133544

>>> +1
1
>>> ++1
1
>>> +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++1
1

Upvotes: 6

Pavel Anossov
Pavel Anossov

Reputation: 62908

In python, that's just unary plus twice. It doesn't do anything. A single one might coerce a bool to an int, but the second one is totally useless.

Upvotes: 10

Related Questions