Reputation: 811
I'm trying to insert some item by index to existing list like this:
c = ['545646', 'text_item', '151561'].insert(1, '555')
print(c)
And I'm getting None in result.
Why I cannot make an insert to the Python list?
The needed output is:
['545646', '555', 'text_item', '151561']
Upvotes: 2
Views: 1455
Reputation: 11
Insert method always returns null .You are trying to print the null type. Therefore do not map insert method to any variable.Use insert as a method and print the original list Try this
c=['545646', 'text_item', '151561']
c.insert(1,55)
print(c)
Upvotes: 1
Reputation: 11550
Try this
c = ['545646', 'text_item', '151561']
c.insert(1, '555')
print(c)
Explanation:
Every python function
call will return some value or None. In case of list.insert()
function call, the return value is None
which you are saving as variable c
which will be None
.
Edit: for follow up question in comment: I'm doing list comprehension and I'm processing the list of the lists. So, every time I would like to change an item in the list using 2 methods insert and pop one by one. How to make these changes while list comprehension?
You should generally avoid list comp
for it's side effect.
instead do:
for sublist in l:
sublist.insert(1, '555') # or call sublist.pop
Upvotes: 5
Reputation: 198324
By Python convention, all mutating functions return None
. Nonmutating functions return the new value. insert
is a mutating function (changes the object it operates on), so it returns None
; you then assign it to c
.
In fact, there is no way to do this in one statement in current Python. In the future (almost certainly in Python 3.8), there is a proposal for a walrus operator that will allow you to shorten this:
(c := ['545646', 'text_item', '151561']).insert(1, '555')
though I believe Pythonistas will frown on it :)
EDIT: With the question in the comments, how to do an insert as an expression? The easiest way is to define another function; for example:
def insert_and_return_list(lst, pos, val):
lst.insert(pos, val)
return lst
c = insert_and_return_list(['545646', 'text_item', '151561'], 1, '555')
You could also avoid insert
altogether, and use slices and splats:
[*lst[:1], '555', *lst[2:]]
Upvotes: 6