k = [[1, 2, 3, 4, 6]] | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
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.

22nd Apr 2019, 10:50 PM
tristach605
tristach605 - avatar
5 Answers
+ 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)
23rd Apr 2019, 5:48 AM
Anna
Anna - avatar
+ 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.
22nd Apr 2019, 11:01 PM
HonFu
HonFu - avatar
+ 1
Thanks HF and JM.
23rd Apr 2019, 2:26 AM
tristach605
tristach605 - avatar
+ 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.
23rd Apr 2019, 5:50 AM
Seb TheS
Seb TheS - avatar
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?
23rd Apr 2019, 11:35 AM
tristach605
tristach605 - avatar