0
k = [[1, 2, 3, 4, 6]]
k = [[1, 2, 3, 4, 6]] k.append(7) k.insert(1,8) print(len(k)) Output: 3 Append means add one thing to the end (a 7 here) and insert means we add two things (a 1 and an 8 here). So should be [[1, 1, 2, 3, 4, 6, 7, 8]] for a total length of 8? Why is the answer 3? Any help appreciated.
5 Réponses
+ 5
You're confusing list.insert and list.extend
k.extend((1, 8)) appends an 1 and an 8 to k (len(k) += 2)
k.insert(1, 8) inserts an 8 at index 1 (len(k) += 1)
+ 4
k is a list that contains another list.
So in the beginning it has a len of 1, because the only element is that inner list.
After 7 is appended and 8 inserted, we have three items in k: the inner list, 8 and 7.
+ 1
Thanks HF and JM.
+ 1
No.
Lists are ordered.
Append adds one to the end of the list item like you said.
Insert also adds only one item, but insert can add the item anywhere in the list.
The list length is 3, because it counts the inner list as one item.
0
k = [[1, 2, 3, 4, 6]]
k.append(7)
k.insert(0,9)
k.insert(2,8)
k.insert(3,10)
k.insert(4,11)
print(len(k))
Thanks for pointint out how insert works. I had forgotten. I did this code to practice. Output is six?