0
Why is 7 and not 8 the answer to this print(len(nums)) quesiton?
What is the result of this code? nums = [9, 8, 7, 6, 5] nums.append(4) nums.insert(2, 11) print(len(nums)) It seems as though append is ignored when the (len(nums)) is printed. Please help, thank you.
3 Answers
+ 3
the first argument of the insert function says the index of the list where you want to place the second argument
when you have this kind of problems try to print out the content of the list. it should be helpful
+ 1
How the length changes:
1. List starts with 5 items (i.e. len(nums) == 5).
2. You call append with one item, now the list is 6 in length.
3. Finally, you inset one item at second position, and now it's 7 in length.
That's it! List nums has a final length of 7.
Why would you think it should be 8!
0
@jehad Al-Ansari Thought it could be 8 because in the lesson before the question it shows
words = ["Python", "fun"]
index = 1
words.insert(index, "is")
print(words)
Result:
>>>
['Python', 'is', 'fun']
>>>
but the question I had to figure out never had line 2 of the lesson "index = 1" which would make since to a nooby since it's showing you the index. The lesson never mentioned anything about nums.insert(2, 11) being shorthand for index = n. Figured the answer out by going step by step in the python interpreter and realizing this after the fact. Thanks for all answers and quick replies.