Why the this extend example is printing 2 two times? - Printable Version +- Python Forum (https://python-forum.io) +-- Forum: Python Coding (https://python-forum.io/forum-7.html) +--- Forum: General Coding Help (https://python-forum.io/forum-8.html) +--- Thread: Why the this extend example is printing 2 two times? (/thread-23674.html) |
Why the this extend example is printing 2 two times? - sbabu - Jan-12-2020 Why the this extend example is printing 2 two times? def my_fun(x): for k in range (len(x)): print('k is ',k) x.extend(x[:k]) print('x is',x) m = [2,4,3] my_fun(m) print(m)Out Put k is 0 x is [2, 4, 3] 0th element is 2 but it does not insert that here. k is 1 x is [2, 4, 3, 2] k is 2 x is [2, 4, 3, 2, 2, 4] After 3 why 2 is being inserted two times [2, 4, 3, 2, 2, 4] RE: Why the this extend example is printing 2 two times? - Gribouillis - Jan-12-2020 The list x is extended by its ks first elements for k in 1, 2, 3, …. Thus x is extended by [] , then by [2] , then by [2, 4] . That's why 2 is appended twice.
|