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

谁说我不能喝 提交于 2019-12-18 01:18:42

问题


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?


回答1:


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.




回答2:


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.




回答3:


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




回答4:


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.




回答5:


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.




回答6:


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.




回答7:


You only need to do myList.append(40)

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



来源:https://stackoverflow.com/questions/12902980/how-to-allow-list-append-method-to-return-the-new-list

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!