4

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?

1
  • 6
    A str can be treated as a sequence and is unpacked. '_##' would have resulted in an error. The same happens with for char in string:. Commented May 9, 2017 at 12:58

2 Answers 2

3

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']
Sign up to request clarification or add additional context in comments.

1 Comment

Ui, interesting. Thank you very much!
3

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.