Mr. President
Mr. President

Reputation: 1549

Add numbers to the beginning of lists

I have a list of list, say X, that looks like this

X_train = [[4,3,1,5], [3,1,6,2], [5,0,49,4], ... , [3,57,3,3]]

I wrote this piece of code

for x in range(0,len(X_train)):
    X_train[x].insert(0, x+1)

For each list in X this code inserts the index value of the list + 1 to the beginning of the list. That is, running

for x in range(0,len(X_train)):
    X_train[x].insert(0, x+1)
print(X)

will produce the following output

[[1,4,1,5],[2,3,1,6,2],[3,5,0,49,4],...,[n,3,57,3,3]]

where n is the number of lists in X.

Question: Is there a faster way to do this? I would like to be able to do this for very large lists, e.g. list with millions of sublists (if that's possible).

Upvotes: 2

Views: 73

Answers (2)

DocDriven
DocDriven

Reputation: 3974

To my knowledge, the standard insert method in Python has a time complexity of O(n). Given your current implementation, your algo would have a time complexity of O(m x n) where m is the number of sublists and n is the number of elements in the sublists (I assume here that the number of sublist elements is always the same).

You could use blist instead of the standard lists which has a time complexity of O(log n) for insertions. This means the total time reduces to O(m x log n). It's not that much of an improvement, though.

Upvotes: 0

blhsing
blhsing

Reputation: 106553

This is faster in my testing:

X = [[n, *l] for n, l in enumerate(X, 1)]

Upvotes: 1

Related Questions