+ 3

Why is this 7 and not 8

Nums = [9, 8, 7, 6, 5] Nums.append(4) Nums.Insert(2,11) Print(len(nums)) Answer 7 . I don’t understand why it’s 7 and not 8. Do we not count the append if insert is after it?

1st Aug 2019, 1:36 AM
Brandon Carpenter
6 Antworten
+ 7
The reason is that the insert() function takes two parameters: index - position where an element needs to be inserted, and element - this is the element to be inserted in the list. So you start with 5 elements, then you append one, so now you have 6 elements, and then insert one at index position 2, so now you have 7 elements, i.e. len(nums) is 7. By the way, you would get an error with the code as you have written it ("nums is not defined") because the first 3 times you refer to your list you use "Nums" and the last time, you use "nums" and Python is case-sensitive. (I'm guessing it's your keyboard auto-capitalizing first letters of first words) :)
1st Aug 2019, 1:49 AM
David Ashton
David Ashton - avatar
+ 6
The 2 is not added Brandon Carpenter . That's just the index or location where the 11 is inserted.
1st Aug 2019, 7:16 AM
Sonic
Sonic - avatar
+ 5
[9, 8, 7, 6, 5] has a length of 5 elements, you append a 4 so now it has a length of 6 elements, now you insert 11 so the list now has a length of 7 elements
1st Aug 2019, 1:47 AM
Jake
Jake - avatar
+ 4
ohps thank you for pointing that out the capital was auto correct but i didnt realize that regardless! but thank both of you i understand now that makes sense!
1st Aug 2019, 1:53 AM
Brandon Carpenter
+ 3
nums =[9,8,7,6,5] nums.append(4) append function is used to add the Element at the end of the list. Now... Element 4 will be added at he end of the list. nums ={9,8,7,6,5,4} nums.Insert(2,11) insert(index,element) insert is a function which takes 2 parameters . index-at which position the element is to be inserted. Element-which element u have to insert into the list. At the second position the element will be inserted nums =[9,8,11,7,6,5,4] Print (len(nums)) "len" is a function which is used to know the length of the list. Length of a list is "7". nums =[9,8,11,7,6,5,4] 1 2 3 4 5 6 7 Answer = "7"
1st Aug 2019, 4:17 PM
PRAKASH BANDI
PRAKASH BANDI - avatar
+ 1
Jake but theres a 2 do we not count that?
1st Aug 2019, 1:48 AM
Brandon Carpenter