DEV Community

tigerfanxiao
tigerfanxiao

Posted on

1

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)

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay