Python multiple string variable declaration

I am trying to figure out what this code does:

printdead, printlive = '_#'

This is from here, a site with implementations of elementary cellular automata: https://rosettacode.org/wiki/One-dimensional_cellular_automata#Python

Apparently, I can replace the above by simply writing

printdead = '_'
printlive = '#'

printdead = '_'; printlive = '#'

printdead, printlive = '_', '#'

and all this is wonderful. But how does the first statement work?

+4
source share
2 answers

It caused iterative unpacking. If the right-hand side of the job is an iterable, you can unpack the values ​​into different names. Lines, lists, and tuples are just a few examples of iterations in Python.

>>> a, b, c = '123'
>>> a, b, c
('1', '2', '3')
>>> a, b, c = [1, 2, 3]
>>> a, b, c
(1, 2, 3)
>>> a, b, c = (1, 2, 3)
>>> a, b, c
(1, 2, 3)

Python 3, Extended Iterable Unpacking .

>>> a, *b, c = 'test123'
>>> a, b, c
('t', ['e', 's', 't', '1', '2'], '3')
>>> head, *tail = 'test123'
>>> head
't'
>>> tail
['e', 's', 't', '1', '2', '3']
+3

.

, , . , .

+3

Source: https://habr.com/ru/post/1676750/


All Articles