2

At several occasions I stumbled upon C-style assignment in Python such as a = b = 0. By diligent Googling I found out that this is called chained assignment: [1],[2],[3]. However, it appears that this feature is not mentioned in the official documentation.

Does this mean that chained assignment is still in experimental phase, or simply that the official documentation is slightly behind the development?

Community
  • 1
  • 1
ssegvic
  • 3,123
  • 1
  • 20
  • 21

2 Answers2

7

Looks like the official documentation does mention it?

assignment_stmt ::=  (target_list "=")+ (expression_list | yield_expression)
                                      ^ here
Anders Johansson
  • 3,926
  • 19
  • 19
  • 1
    @ssegvic: as well as the narrative text below it: *and assigns the single resulting object to each of the target lists, from left to right.* – Martijn Pieters Dec 27 '12 at 14:39
  • `from left to right` is important! Notice that `ys=[None]; zs=[True]; xs=ys; xs=xs[0]=zs` has the effect of first doing `xs=zs` then making `xs` be a circular list whose first element is itself. The parallel syntax in C would instead do `xs[0]=zs`, and then rebind `xs` to `zs`. To achieve the C behavior in Python, you'd have to instead do `xs[0] = xs = zs`. The parallel syntax to *that* in C would fail. This can trip one up if converting between C and Python! – dubiousjim Dec 15 '18 at 15:54
0

You can use chain assignment, but it is not Pythonic style.

From the The Zen of Python;; "Flat is better than nested. "

cengizkrbck
  • 704
  • 6
  • 21