+ 2

list appends a list in python

Can someone explain how it works? x = [1,1,2,3,6] x.append(x[:]) print(len(x)) outputs>>>> 6 x = [1,1,2,3,6,[...]] What means this [...]?

14th Apr 2018, 5:01 PM
HBhZ_C
HBhZ_C - avatar
13 ответов
+ 8
are you sure it's x.append(x[:]) and not x.append(x) ?
14th Apr 2018, 5:31 PM
Burey
Burey - avatar
+ 8
Hechmi Barhouma nope, x isn't the same as x[:] x is the list instance itself, while x[:] should create a new identical list (duplicate the object) the weird thing is this tho: in your code you append x[:], which should result in the following list: [1, 1, 2, 3, 6, [1, 1, 2, 3, 6]] if you append x on the other hand, you should get this list: [1, 1, 2, 3, 6, [ ... ]] and that is because your x list is now contained in itself infinitely [1, 1, 2, 3, 6, [1, 1, 2, 3, 6,[1, 1, 2, 3, 6, [1, 1, 2, 3, 6, [ ... ]]]]] basically it would look like this x --> [1, 1, 2, 3, 6, x ] |________________|
14th Apr 2018, 5:40 PM
Burey
Burey - avatar
+ 8
oh great glad it's clear ^_^
14th Apr 2018, 5:48 PM
Burey
Burey - avatar
+ 2
Yes sure,why?x[:] is in't the same as x Burey??
14th Apr 2018, 5:34 PM
HBhZ_C
HBhZ_C - avatar
+ 2
Ah thanks Burey,it is clear now.Good explanation.
14th Apr 2018, 5:46 PM
HBhZ_C
HBhZ_C - avatar
+ 1
What do you means Tianerad party game??
14th Apr 2018, 5:21 PM
HBhZ_C
HBhZ_C - avatar
+ 1
First of all the "len" keyword counts the number of items are there in the list as list can contain more list. and the "len" keyword considers it as a single item. and second x[:] is not same as x. because example: consider x = [1,2] b = x. output = [1,2] c = x[:]. output = [1,2] as you can see the output is same But the main difference is that b is assigned to the same memory in which the value of x ([1,2]) is stored. and c is assigned to the different memory for the same value of x ([1,2])
14th Apr 2018, 7:59 PM
Salman
Salman - avatar