+ 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 [...]?
13 Respuestas
+ 8
are you sure it's x.append(x[:]) and not x.append(x) ?
+ 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 ]
|________________|
+ 8
oh great
glad it's clear ^_^
+ 2
Yes sure,why?x[:] is in't the same as x Burey??
+ 2
Ah thanks Burey,it is clear now.Good explanation.
+ 1
What do you means Tianerad party game??
+ 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])