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

前端 未结 7 1581
春和景丽
春和景丽 2020-12-09 00:31

I want to do something like this:

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

Unfortunately, list append does not return the modified

相关标签:
7条回答
  • 2020-12-09 00:55

    You only need to do myList.append(40)

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

    0 讨论(0)
  • 2020-12-09 01:03

    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.

    0 讨论(0)
  • 2020-12-09 01:06

    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.

    0 讨论(0)
  • 2020-12-09 01:11

    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.

    0 讨论(0)
  • 2020-12-09 01:16

    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

    0 讨论(0)
  • 2020-12-09 01:20

    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.

    0 讨论(0)
提交回复
热议问题