Lenna
Lenna

Reputation: 1465

Where does the list assignment go?

A number of Python's list methods operate in place and return None (off the top of my head, insert, sort, reverse).

However, there is one behavior that frequently frustrates me. If I create a new list, which normally returns an object, and insert on it at the same time, the new list "disappears":

mytup = (0, 1, 2, 3, 4)
print mytup  # (0, 1, 2, 3, 4)
mylist = list(mytup)
print mylist  # [0, 1, 2, 3, 4]
newlist = list(mytup).insert(0, 10)
print newlist  # None

So if I want to modify a tuple, it requires more lines:

newlist = list(mytup)
newlist.insert(0, 10)
print newlist  # [10, 0, 1, 2, 3, 4]

So I have two questions:

  1. Is it correct to say that when I call the list constructor, it returns the object, but when I call the list constructor with a method on it, the method "overrides" the return with None? Again, where does the list go?
  2. Is there a way to insert into a tuple and return a list in one line? I am not trying to play code golf, I just don't think the two lines are logically different enough to merit separation.

Upvotes: 2

Views: 96

Answers (2)

Thijs van Dien
Thijs van Dien

Reputation: 6616

The answer to your first question has already been given; you assign to the variable the result of the last function call, which is None. Here's the answer to your second question.

Rather than using insert, do something like this:

newlist = [10] + list(mytup)

It creates a new list containing the element to be inserted, appends it to the converted tuple and stores (a reference to) the resulting list.

This, of course, only works if you want to insert on either end.

If you need the new element to be inserted somewhere else, you have to slice the tuple, e.g. to insert after the third element in the tuple:

newlist = list(mytup[:3]) + [10] + list(mytup[3:])

Upvotes: 1

Ashwini Chaudhary
Ashwini Chaudhary

Reputation: 250961

insert,sort and reverse modify the list in-place and return None. And in your code you're actually storing that returned value in the newlist variable.

newlist = list(mytup).insert(0, 10)

And that newly created list(created on the fly) is garbage collected as there are no references to it any more.

In [151]: mytup = (0, 1, 2, 3, 4)

In [152]: lis=list(mytup)   #create a new list object and add a reference to this new object

In [153]: newlist=lis.insert(0,10)  #perform the insert operation on lis and store None
                                    # in newlist 

In [154]: print newlist     
None

In [155]: print lis     
[10, 0, 1, 2, 3, 4]  #you can still access this list object with 
                     #the help of `lis` variable.

Upvotes: 3

Related Questions