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

Question:

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?

Asked By: Wilk

||

Answers:

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.

Answered By: Martijn Pieters

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

Answered By: inspectorG4dget

You only need to do
myList.append(40)

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

Answered By: Storstamp

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.

Answered By: Marcin Wyszynski

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.

Answered By: jsears

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.

Answered By: ajayinvictus10

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.

Answered By: Damian Paszkowski

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.

Answered By: dawid
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.