How to allow list append() method to return the new list

PythonListAppend

Python Problem Overview


I want to do something like this:

myList = [10, 20, 30]
yourList = myList.append(40)

Unfortunately, list append does not return the modified list.

So, how can I allow append to return the new list?

Python Solutions


Solution 1 - Python

Don't use append but concatenation instead:

yourList = myList + [40]

This returns a new list; myList will not be affected. If you need to have myList affected as well either use .append() anyway, then assign yourList separately from (a copy of) myList.

Solution 2 - Python

In python 3 you may create new list by unpacking old one and adding new element:

a = [1,2,3]
b = [*a,4] # b = [1,2,3,4] 

when you do:

myList + [40]

You actually have 3 lists.

Solution 3 - Python

list.append is a built-in and therefore cannot be changed. But if you're willing to use something other than append, you could try +:

In [106]: myList = [10,20,30]

In [107]: yourList = myList + [40]

In [108]: print myList
[10, 20, 30]

In [109]: print yourList
[10, 20, 30, 40]

Of course, the downside to this is that a new list is created which takes a lot more time than append

Hope this helps

Solution 4 - Python

Try using itertools.chain(myList, [40]). That will return a generator as a sequence, rather than allocating a new list. Essentially, that returns all of the elements from the first iterable until it is exhausted, then proceeds to the next iterable, until all of the iterables are exhausted.

Solution 5 - Python

You can subclass the built-in list type and redefine the 'append' method. Or even better, create a new one which will do what you want it to do. Below is the code for a redefined 'append' method.

#!/usr/bin/env python

class MyList(list):

  def append(self, element):
    return MyList(self + [element])


def main():
  l = MyList()
  l1 = l.append(1)
  l2 = l1.append(2)
  l3 = l2.append(3)
  print "Original list: %s, type %s" % (l, l.__class__.__name__)
  print "List 1: %s, type %s" % (l1, l1.__class__.__name__)
  print "List 2: %s, type %s" % (l2, l2.__class__.__name__)
  print "List 3: %s, type %s" % (l3, l3.__class__.__name__)


if __name__ == '__main__':
  main()

Hope that helps.

Solution 6 - Python

Just to expand on Storstamp's answer

You only need to do myList.append(40)

It will append it to the original list,now you can return the variable containing the original list.

If you are working with very large lists this is the way to go.

Solution 7 - Python

Unfortunately, none of the answers here solve exactly what was asked. Here is a simple approach:

lst = [1, 2, 3]
lst.append(4) or lst  # the returned value here would be the OP's `yourList`
# [1, 2, 3, 4]

One may ask the real need of doing this, like when someone needs to improve RAM usage, do micro-benchmarks etc. that are, usually, useless. However, sometimes someone is really "asking what was asked" (I don't know if this is the case here) and the reality is more diverse than we can know of. So here is a (contrived because out-of-a-context) usage... Instead of doing this:

dic = {"a": [1], "b": [2], "c": [3]}

key, val = "d", 4  # <- example
if key in dic:
    dic[key].append(val)
else:
    dic[key] = [val]
dic
#  {'a': [1], 'b': [2], 'c': [3], 'd': [4]}

key, val = "b", 5  # <- example
if key in dic:
    dic[key].append(val)
else:
    dic[key] = [val]
dic
#  {'a': [1], 'b': [2, 5], 'c': [3], 'd': [4]}

One can use the OR expression above in any place an expression is needed (instead of a statement):

key, val = "d", 4  # <- example
dic[key] = dic[key].append(val) or dic[key] if key in dic else [val]
#  {'a': [1], 'b': [2], 'c': [3], 'd': [4]}

key, val = "b", 5  # <- example
dic[key] = dic[key].append(val) or dic[key] if key in dic else [val]
#  {'a': [1], 'b': [2, 5], 'c': [3], 'd': [4]}

Or, equivalently, when there are no falsy values in the lists, one can try dic.get(key, <default value>) in some better way.

Solution 8 - Python

You only need to do myList.append(40)

It will append it to the original list, not return a new list.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionWilkView Question on Stackoverflow
Solution 1 - PythonMartijn PietersView Answer on Stackoverflow
Solution 2 - PythonDamian PaszkowskiView Answer on Stackoverflow
Solution 3 - PythoninspectorG4dgetView Answer on Stackoverflow
Solution 4 - PythonjsearsView Answer on Stackoverflow
Solution 5 - PythonMarcin WyszynskiView Answer on Stackoverflow
Solution 6 - Pythonajayinvictus10View Answer on Stackoverflow
Solution 7 - PythondawidView Answer on Stackoverflow
Solution 8 - PythonStorstampView Answer on Stackoverflow