5 ms·
Since append doesn't return a value, how about: def append_one(var=None): return (var or []) + [1] Would this take longer and/or use more storage for
by gshubert17 12y ago
Since append doesn't return a value, how about:
def append_one(var=None):
return (var or []) + [1]
Would this take longer and/or use more storage for long lists as vars?
- keeperofdakeys 12y agoWhen you use + on two lists, a new list is created, and elements from both are copied into the new one. Whereas the append operation modifies the list, and simply adds a value. Keep in mind that a python "list" is really like a C++ vector, so while sometimes append operation sometimes allocates a new array, and copies all the values, in general is O(1). The add operation is O(n). And besides all that, there is nothing wrong with doing an append on one line, and returning the variable on the next. It's clear and readable.
- SEJeff 12y agoI like this, very elegant actually.