Wiki
Version 5 (modified by torial, 8 years ago)

fixed typo

Multi Variable or Multi Target Assignments

Cobra supports multi variable or multi target assignment

a, b, c = 10, 20, 30  # comma separated list of expressions

# or
a, b, c = [10, 20, 30] # list literal

# or
alist = [10, 20, 20]
a, b, c = alist       # an arbitrary list variable

assert a == 10
assert b == 20
assert c == 30

These are expected to give the same results as if the assignment target and source lists were unrolled and each assignment done individually

a = 10
b = 20
c = 30

a = alist[0]
b = alist[1]
c = alist[2]

The targets must be a comma separated list, the items of which are things that can be assigned a value - any of local variables, class or instance variables, properties or indexers.

The assignment sources can be a single expression that resolves to a list, array or String (specifically any expression that supports an integer indexer)

or

a comma separated stream of expressions.

# unusual but acceptable - dict keyed by int in range
dict = {1:'aye', 2:'bee'}
a, b = dict
assert a == 'aye'
assert b == 'bee'

# assignment to an expression list
a, x, c = 99+1, 'xxx'+'y', 2*2
assert a == 100
assert x == 'xxxy'
assert c == 4

The size of the target and source lists are expected to match as if the assignments were done individually.

The target source values are atomic in value for the duration of the assignments.

Multi Targets in a 'for loop'

Multiple targets can also be provided in a for loop covering an enumerable source.

If the enumerable source is a Dictionary there may be only 2 targets and they get filled with the next key and keyValue from the dictionary for the loop block

dict = {'x':'aye', 'y':'bee'}
for k, v in dict
    print 'key=', k, 'value=', v
    assert k in ['x', 'y']
    assert v in ['aye', 'bee']

Otherwise the enumerable source is expected to generate a list of items of the same size as the list of targets for each step of the enumeration

for i, j in [1, 2, 3, 4]    # error
    pass

for i, j in [[1, 2], [3, 4]]
    assert i in [1, 3]
    assert j in [2, 4]

If you want to get multiple values from an enumeration generating non list (single) values the current idiom is to use a for expression

i, j = for x in [1, 2, 3, 4] get x

alist = [1, 2, 3, 4]
i, j = for x in alist get x