The actual reason why you can't do either of the following,
l = [].append(2)
l = [2,3,4].append(1)
is because .append() always returns None as a function return value. .append() is meant to be done in place.
See here for docs on data structures. As a summary, if you want to initialise a value in a list do:
l = [2]
If you want to initialise an empty list to use within a function / operation do something like below:
l = []
for x in range(10):
value = a_function_or_operation()
l.append(value)
Finally, if you really want to do an evaluation like l = [2,3,4].append(), use the + operator like:
l1 = []+[2]
l2 = [2,3,4] + [2]
print l1, l2
>>> [2] [2, 3, 4, 2]
This is generally how you initialise lists.
Answer from Alexander McFarlane on Stack OverflowCan we make a one-liner the pattern "if the object is a list, append a value to it, otherwise initialize it with an empty list and append the value to it"
Quick way to append non-blank elements in a list to another list?
What happens when we append an empty list to itself in python ?
python - Appending an empty list to a list does append previous list contents - Stack Overflow
What I mean is this:
if not banned_users:
banned_users = []
banned_users.append("foo")
or even this (supposing we have a dictionary cache={}):
if not cache.get("banned_users"):
cache["banned_users"] = []
cache["banned_users"].append("foo")In some languages this can be done a one-liner with the null-coalescing operator
(banned_users ??= []).append("foo")is there a way with Python to make it a one-liner or at least a "two-liner"?