Home > Python list.insert(i,x) weird behavior?
Python list.insert(i,x) weird behavior?
- By Admin
- Posted On June 15, 2011 At 3:33 pm
- In Category List Building
When I used list.insert(i,x) , I assumed that it will replace the current value x at position i with a new value of x at position i. When I test the list, I got these weird results.
1. 5 elements built into list L
[0, 1, 2, 3, 4, 5]
2. Going back and trying to override number 4, I get.
[0, 1, 2, 3, 4, 4, 5]
List grows on insertion of previous value. Wat?
That is exactly what insert does. Were you confused by the paragraph 5.6.4 “Mutable sequence types” http://docs.python.org/library/stdtypes.html#sequence-types-str-unicode-list-tuple-buffer-xrange which said that s.insert(i, x) is the same as s[i:i] = [x] ? Note how different that is from what you want to do, which is s[i] = x.
(try printing out L[4:4] to see what elements that slice contains, for example)