+ 2

confused

Does this mean that for each new item you need to insert them separately? What is the result of this code? nums = [9, 8, 7, 6, 5] nums.append(4) nums.insert(2, 11) print(len(nums)) The result is 7, I thought it would be 8

18th Feb 2017, 5:38 PM
Matthew Luvera
3 Respostas
+ 16
As pablits said you put 11 in the 2nd index and Third position I.e num.insert(2,11) give you num = [9,8,11,7,6,5] As you can see 11 was inserted in the 2nd index I.e [0th index=9,1st index=8,2nd index=7,3rd index=6,4th index=5] so 11 was inserted into the second index and 7th was shifted to the 3rd, and 6 the 4th, and finally 5 the 5th. This is because the insert method of an object takes can take two argument the first the value to be inserted, and the second the index of the place the value is to be inserted into.
18th Feb 2017, 6:21 PM
Josephine Smith
Josephine Smith - avatar
+ 3
You can append more than one new item with list concatenation: nums = [ 9, 8, 7, 6, 5 ] nums.append(4) # now nums == [ 9, 8, 7, 6, 5, 4 ] nums = nums + [ 2, 11 ] # nums == [ 9, 8, 7, 6, 5, 4, 2, 11 ] and now len(nums) == 8 # or: nums += [ 2, 11 ] Or with extend() list method... nums = [ 9, 8, 7, 6, 5, 4 ] nums.extend([2,11]) # nums == [ 9, 8, 7, 6, 5, 4, 2, 11 ] and len(nums) == 8 And to insert many items at a specific position ( index ), use slice syntax: nums = [ 9, 8, 7, 6, 5, 4 ] nums[3:3] = [ 2, 11 ] # nums == [ 9, 8, 7, 2, 11 6, 5, 4, ] and len(nums) == 8
19th Feb 2017, 8:09 AM
visph
visph - avatar
+ 2
nums.insert(2,11) you put 11 in the 3rd position. if you print (nums) u will understand ;)
18th Feb 2017, 5:42 PM
Pablits
Pablits - avatar