Assign and increase value on one line

Is it possible to assign a value and increment an assigned value on the same line in Python?

Something like that:

x = 1 a = x b = (x += 1) c = (x += 1) print a print b print c >>> 1 >>> 2 >>> 3 

Edit: I need this in the context where I create an Excel sheet:

 col = row = 1 ws.cell(row=row, column=col).value = "A cell value" ws.cell(row=row, column=(col += 1)).value = "Another cell value" ws.cell(row=row, column=(col += 1)).value = "Another cell value" 

Edit 2: Solution: This is not possible, but I created an easy fix:

 col = row = 1 def increment_one(): global col col += 1 return col ws.cell(row=row, column=col).value = "A cell value" ws.cell(row=row, column=increment_one()).value = "Another cell value" ws.cell(row=row, column=increment_one()).value = "Another cell value" 
+7
python
source share
3 answers

No, this is not possible in Python.

Assignments (or additional tasks ) are statements and as such cannot appear on the right side of another task. You can only assign expressions to variables.

The reason for this is most likely to avoid the confusion of side effects that are easily caused in other languages ​​that support this.

However, regular assignments support multiple goals, so you can assign the same expression to multiple variables. This, of course, still allows you to have only one expression on the right side (still not specified). In your case, since you want b and x be in the same value, you can write it as follows:

 b = x = x + 1 c = x = x + 1 

Note that since youre doing x = x + 1 , you no longer use the extended assignment and, as such, may have different effects for some types (but not integers).

+7
source share

Not very pretty, but you can do something like this.

 x = 1 a = x x = b = x+1 x = c = x+1 >>> print a,b,c >>> 1,2,3 >>>print id(a),id(b),id(c),id(x) >>>31098952 31098928 31098904 31098904 
+4
source share

You can do this with a function, here I use the lambda function. The exact python equivalent of ++x or x++ in c.

not.
 inc =lambda t: t+1 x = 1 a = x b,x=inc(x),x+1 c,x = inc(x),x+1 print a print b print c 
+3
source share

All Articles