Search code examples
pythonfunctionmethodsoperator-keywordextend

How to extend lists without list.extend method and without '+' operator


I am tring to do an extending function, one that will work as list.extend method, but i don't want it to contain list.extend method or the '+' operator, and in addition I need to extend 'x' and not to 'y' (you will see).

first of all, this is x and y:

x = [4, 5, 6]
y = [1, 2, 3]

I tried this: x = y, x But it is giving me this result: ([1, 2, 3], [4, 5, 6]), and I ran out of ideas...

The thing that I want to do (without extend method and '+' operator) will look like this:

x = [4, 5, 6]
y = [1, 2, 3]
extending_func(x, y)
[1, 2, 3, 4, 5, 6]

I want to do a function like "extending_func" but I dont succes to bring it all to one list, and i dont know if i need to chage the type of list to somthing else to do it, or that I need just a simple idea to solve it. I tried also to use list.append, but it is giving me the next result (just to try the idea, but as i wrote i need to extend x and not y):

x = [4, 5, 6]
y = [1, 2, 3]
y.append(x)
[1, 2, 3, [4, 5, 6]]

Solution

  • Append y to x using list slicing:

    x = [4, 5, 6]
    y = [1, 2, 3]
    x[:0] = y
    print(x)  # [1, 2, 3, 4, 5, 6]
    

    Just note that the order you append the lists in is very important in this case; y = [1, 2, 3] is being added in front (at index 0) of x = [4, 5, 6] (see this tweak by Jean-François Fabre for a better method)