Reputation: 1458
I am surprised by the behavior of List Comprehension
on a list
of lists
. I would expect List comprehension
to return a new list to me ALWAYS. For example:
>>> L = [1,2,3,4,5,6]
>>> M = [ x * 2 for x in L]
>>> L
>>> [1,2,3,4,5,6]
>>> M
>>> [2,4,6,8,10,12]
So L
is not changed.
However,
>>> L = [[1], [2], [3]]
>>> M = [x.append(100) for x in L]
>>> M
>>> [None, None, None]
>>> L
>>> [[1,100], [2,100], [3,100]]
Now L is changed and list comprehension
does not return a new List.
I am expecting a new List by the list comprehension. Any explanation would help me to understand this behavior of list comprehension
Upvotes: 0
Views: 808
Reputation: 2648
You are appending to x
, is an element in L
, that is why L
changes. If you want a new list do not mutate a older, create a new one.
You don't specify a result you expect, but I believe this what your looking for:
>>> L = [[1], [2], [3]]
>>> M = [[*x, 100] for x in L]
>>> L
[[1], [2], [3]]
>>> M
[[1, 100], [2, 100], [3, 100]]
Upvotes: 1
Reputation: 2518
x * 2
is an expression which evaluates to a result and its result will be stored in the list M
.
x.append(100)
on the other hand applies function append()
on the object x
, which is an element of list L
and returns None
.
It is the same, why you do y = x * 2
, but not y = x.append(100)
.
Upvotes: 2
Reputation: 51
x.append(100)
Return nothing(None), this why you have only None's inside M.
Upvotes: 0