Reputation: 29
n1, n2, n3 = (n + [None]*2)[:3]
I just very briefly want to know what this does, how this works. Is this like a list comprehension, as long as I offer a list or iterable with enough variables will it assign the n1 = iterable[0]?
Also why does having [:3] on the end of the brackets limit the length?
I understand why [None] is there, just in case the length of n is less than 3 but can someone give me a bit more info?
I have only been coding for about a week and need a bit of help interpreting.
Upvotes: 2
Views: 95
Reputation: 11302
This is not list comprehension. Presumably, n
is a list, or anything that can be the left-operand of concatenation by the +
operator when called with the suitable right-operand, under suitable implementation of __add__
or __radd__
. The +
operator on lists concatenates them together to create a new list, and the [:3]
part is just syntax sugar for getting a slice of the list. You really should look up the documentation.
Upvotes: 3
Reputation: 25478
This takes the first three elements of n
, padding with None
if it has fewer than three elements.
(n + [None]*2)
concatenates a list of [None, None]
to the list n
, and as you say, [:3]
takes the first three items of the resulting list. These three items are then unpacked to the variables n1
, n2
and n3
.
For example:
In [1]: n = ['One', 'Two']
In [2]: n1, n2, n3 = (n + [None]*2)[:3]
In [3]: print n1
One
In [4]: print n2
Two
In [5]: print n3
None
But if n
has three or more items in it, you just get those three items as n1
, n2
and n3
.
As others have noted below, this code will fail if n
is the empty list, since then (n + [None]*2)
will only have two items in it. It can be sliced OK: (n + [None]*2)[:3]
returns a list with those two items, but then the unpacking to three variables fails. Whether the resulting ValueError
in this case is the intended exception to be raised or whether the code should be n1, n2, n3 = (n + [None]*3)[:3]
so as to return None
into each of the variables is something only the original programmer knows. This would usually warrant a comment in the code.
Upvotes: 7