Python Forum

Full Version: Why the this extend example is printing 2 two times?
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
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]
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.