DEV Community

tigerfanxiao
tigerfanxiao

Posted on

Do not use append/extend in Python Comprehension expression

One mistake which for me almost one hour to debug is that I used list method append in the python comprehension expression.

Take a look at belows to assignment, check which one will have output of [[1, 4], [2, 4]]

# first 
[subset.append(4) for subset in [[1], [2]] 
# second
[subset + [4] for subset in [[1], [2]]
Enter fullscreen mode Exit fullscreen mode

Actually the second one is correct, and with the first one, you will get [None]. Why? Because list method like append or extend does not have return value, they just modify the original list. For that reason you got None when you tried to do some operation on a list.

Be careful of those methods which don't have return value when you are trying to use them in comprehension expression in Python.

Top comments (0)