Search code examples
pythonlistvectorizationprepend

Is there a efficient way to prepend a list from items from another list?


Given two list, the goal is to append the items from the 2nd list to the 1st and return the matrix of lists, e.g.

x = [1, 2, 3, 4, 5]
y = [123, 456]  # m no. of items

def func(x, y):
  return [[i] + x for i in y]

func(x, y)

[out]:

[[123, 1, 2, 3, 4, 5], [456, 1, 2, 3, 4, 5]]

While this works for small no. of items in y, having O(m) is kind of expensive. Is there an efficient way to optimize this prepending? Or O(m) is the best possible?


Solution

  • If you're going to produce an output with m different values O(m) is the best you can do. In this case, you'll also be processing the n values of x m times so it's going to end up O(mn).

    Assuming that Python's internal copy() method is faster than a concatenation plus a list creation, you could setup a template list and make a copy at each iteration witht the first item populated from the other list:

    x = [1, 2, 3, 4, 5]
    y = [123, 456]
    
    def func(x, y):
        template = [0]+x
        return  [template.copy() for template[0] in y]
    
    print(func(x,y))
    [[123, 1, 2, 3, 4, 5], [456, 1, 2, 3, 4, 5]]