'Assigning empty list

I don't really know how I stumbled upon this, and I don't know what to think about it, but apparently [] = [] is a legal operation in python, so is [] = '', but '' = [] is not allowed. It doesn't seem to have any effect though, but I'm wondering: what the hell ?



Solution 1:[1]

This is related to Python's multiple assignment (sequence unpacking):

a, b, c = 1, 2, 3

works the same as:

[a, b, c] = 1, 2, 3

Since strings are sequences of characters, you can also do:

a, b, c = "abc"    # assign each character to a variable

What you've discovered is the degenerative case: empty sequences on both sides. Syntactically valid because it's a list on the left rather than a tuple. Nice find; never thought to try that before!

Interestingly, if you try that with an empty tuple on the left, Python complains:

() = ()            # SyntaxError: can't assign to ()

Looks like the Python developers forgot to close a little loophole!

Solution 2:[2]

Do some search on packing/unpacking on python and you will find your answer. This is basically for assigning multiple variables in a single go.

>>> [a,v] = [2,4]
>>> print a
2
>>> print v
4

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1
Solution 2 saurabh baid