user1836262
user1836262

Reputation: 143

Python - how to shorten operations

I know in Java if you want to add one to a variable you can use x++ is there anything similar to this in Python.

Upvotes: 0

Views: 482

Answers (2)

Hyperboreus
Hyperboreus

Reputation: 32449

You can use

x += 1

Increment operator does not exist in python.

As Lattyware pointed out, there is not as much need for an increment operator as in e.g. Java or C. If you have a loop that relies on i+=1 in python, you maybe want to rethink your code.

Just as an example:

Avoid:

idx = 0
for e in L:
    print (idx, e)
    idx += 1

for idx in range (len (L) ): print (idx, L [idx] )

Try:

for idx, e in enumerate (L): print (idx, e)

Also, when the sequences you need are beyond the scope of pure integer ranges (e.g. yielding strings or objects or anything), you should think about generators:

def weirdSequence (v):
    while True:
        yield v
        if v == 1: break
        v = v * 3 + 1 if v % 2 else v // 2

for i in weirdSequence (7): print (i)

Upvotes: 4

Thomas
Thomas

Reputation: 6762

As Hyperboreus says, no x++ operator in Python. I think it's interesting to guess at why - I think it's that Python makes a point of assignment not being an expression, and users of x++ experienced in other languages might expect the result of this expression to be the un-incremented value of x. If assignment isn't an expression with a value, then there is not difference between x++ and ++x. I think having one of these but not the other would be confusing, but having them both do the same thing would be redundant.

Upvotes: 0

Related Questions