+ 6
Problem in two python challenges
Nums=[9,8,7,6,5,4] Nums.insert(2,11) Print(len(Nums)) Answer is 7. But why not 8? ....................... L, D = [], [] for x in range(4): D.append(x) L.append(D) Print(L) Answer is [0,1,2,3] four times. But I think it will be [[0],[0,1],[0,1,2],[0,1,2,3]]. Finally, I think I don't know append and insert well. Please explain them for me. Thanks.
8 Réponses
+ 3
With extending lists I recommend to keep in mind these 3 list methods:
list.append
list.insert
list.extend
I expect you know list.append, but I mention it anyways.
list.append
Is used to add one single item in the end of the list.
x.append(y) equals x[len(x):] = [y]
list.insert
Is used to add one single item in any index of the list, in the index an item is inserted, it will push the following items 1 step forward.
x.insert(y, z) equals x[y:y] = [z]
list.extend
Is used to append all the items of any iterables to the end of the list.
x.extend(y) equals x[len(x):] = list(y)
+ 6
Thanks Thomas Williams. It seems like if you insert something like(10,11) the 11 will be in the last place of the list(here:6). Am I right?
+ 6
Thank you Seb TheS. The explanation is really amazing.
+ 3
The first argument in insert() indicates position. It is telling the interpreter to insert 11 at the second index
+ 3
Python lists may sometimes be quite complicated.
Because when you assign variables, the variables are not actually the values self, variables in Python are just keys to the values they were assigned.
When you appended D in L, you did not give a copy of D's value, you made a copy of the key to the D's value, the value can change, because lists are mutable.
In the end you have added 4 copies of keys of D's value to the list L, when you printed L, you got the D's final value 4 times.
This could be fixed by changing L.append(D)
To any of these:
L.append(D.copy())
L.append(list(D))
L.append(D[::])
Using D.copy is the most recommended way.
+ 2
If the index does not exist you will get an error. For example an index of 10 in a list of 4 values would raise an error👍🏼
+ 1
AZunderstars Thanks, nice you found them interesting.