0

In python, lists have an insert method, which returns None.

li = ['a','b']
print li.insert(1,'a')
None

I need it to return the list,

print li.insert(1,'a')
['a','a','b']

I am trying to do it by creating a new class, but I am stuck

class Nlist(list):
    def insert(self,*args,**kwargs):
        super(Nlist,self).insert(*args,**kwargs)
        return #what?
yayu
  • 7,758
  • 17
  • 54
  • 86
  • I feel like I might be missing something but is there a reason you can't just print the new list with `print li`? If there is a reason this is insufficient then you should edit the question and explain why and explain the use case involved. – shuttle87 Jun 25 '14 at 15:14
  • @shuttle87 I can, but I am trying to do this simple override so that I don't have to use an extra variable for a temporary assignment. – yayu Jun 25 '14 at 15:20
  • I'm not sure I understand, lists are mutable so you have to have modified a preexisting list when using `insert`. How does an extra variable for temporary assignment come into this? – shuttle87 Jun 25 '14 at 15:31
  • @shuttle87 it might be stupid, but I have a string, which doesn't have an insert method, so i convert it to a list, apply insert, then use join to reconvert it to a string, all in a list comprehension where there are several strings iterated over. I'll think of a better way, but right now this solves my problem. – yayu Jun 25 '14 at 15:36
  • insert just doesn't return anything - it changes the list inplace so do the insert then print the list – gkusner Jun 25 '14 at 15:40
  • 1
    @yayu What you've just described is an [X-Y problem](http://meta.stackexchange.com/questions/66377/what-is-the-xy-problem). Ask about your initial problem, not about the workaround you've come up with. – kojiro Jun 25 '14 at 15:48

2 Answers2

2

You can subclass list like this:

class Nlist(list):
    def insert(self, *args, **kwargs):
        super(Nlist, self).insert(*args, **kwargs)
        return self
Nathaniel
  • 770
  • 7
  • 14
  • (But, don't do this...) – Andrew Jaffe Jun 25 '14 at 15:17
  • 1
    Well, it's not very "pythonic" -- but it's not without some controversy (e.g., http://stackoverflow.com/questions/11017364/should-internal-class-methods-returnvalues-or-just-modify-instance-variables-in, http://stackoverflow.com/questions/17459970/python-class-methods-when-to-return-self, http://programmers.stackexchange.com/questions/29657/purpose-of-return-self-from-a-class-method) – Andrew Jaffe Jun 25 '14 at 15:48
0

instead of

    li = ['a','b']
    print li.insert(1,'a')
    None

do this

    li = ['a','b']
    li.insert(1,'a')
    print li
    ['a','a','b']
gkusner
  • 1,244
  • 1
  • 11
  • 14