Python insertion not getting desired results?

#!/usr/bin/python numbers = [1, 2, 3, 5, 6, 7] clean = numbers.insert(3, 'four') print clean # desire results [1, 2, 3, 'four', 5, 6, 7] 

I get no. What am I doing wrong?

+4
source share
4 answers

Mutating methods in lists usually return None , not an unmodified list, as you would expect - such methods do their job by modifying the list in place rather than creating and returning a new one. Thus, print numbers instead of print clean will show you the changed list.

If you need to keep numbers intact, first make a copy, then you change the copy:

 clean = list(numbers) clean.insert(3, 'four') 

this has a general effect that you think is desirable: numbers does not change, clean is a changed list.

+14
source

The insert method modifies the list in place and does not return a new link. Try:

 >>> numbers = [1, 2, 3, 5, 6, 7] >>> numbers.insert(3, 'four') >>> print numbers [1, 2, 3, 'four', 5, 6, 7] 
+7
source
Insert

inserts an item into this list. Instead, print the numbers and you will see your results. insert does not return a new list.

+1
source

The list.insert () statement returns nothing that you probably want:

 print numbers 
+1
source

All Articles