Frank Haubenreisser
Frank Haubenreisser

Reputation: 337

Multiple string variable declaration python

I'm trying to figure out what this code does:

printdead, printlive = '_#'

It's 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 statement by simply writing

printdead = '_'
printlive = '#'

printdead = '_'; printlive = '#'

printdead, printlive = '_', '#'

which is all perfectly fine by me. But how does the first statement work?

Upvotes: 4

Views: 1713

Answers (2)

timgeb
timgeb

Reputation: 78780

It's called iterable unpacking. If the right hand side of an assignment is an iterable object, you can unpack the values into different names. Strings, lists and tuples are just a few examples of iterables 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)

If you are using Python 3, you have access to Extended Iterable Unpacking which allows you to use one wildcard in the assignment.

>>> 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']

Upvotes: 3

fonfonx
fonfonx

Reputation: 1465

You are correct.

The first statement will split the string given as input in one character strings and unpack the list. Therefore with this syntax you need as many variables in the left hand side expression as characters in your string.

Upvotes: 3

Related Questions