Create subList of list, with increased performance


Let’s say we’ve got a few lists as follows:

list1 = ['hi', 'hello', 'goodbye', 'caio', 1.0]
list2 = ['hi', 'bye', 1.0] 
list3 = ['hi', 'bye', 'hello', 2.0]

I want to get it in this format:

newList1 = [['hi', 'hello'], ['hello', 'goodbye'], ['goodbye', 'caio'], ['caio', 1.0]]
newList2 = [['hi', 'bye'], ['bye', 1.0]] 
newList3 = [['hi', 'bye'], ['bye', 'hello'], ['hello', 2.0]]

My current method is looping through the list based on len(), and appending [listN[i], listN[i+1], but this is running within another for loop of a huge dataset, so O(n^2) is brutal. Is there any way to increase the performance?


Asked By: Ev0



You can do like this,

list1 = ['hi', 'hello', 'goodbye', 'caio', 1.0]

newList1 = list(zip(list1, list1[1:]))
# Result
[('hi', 'hello'), ('hello', 'goodbye'), ('goodbye', 'caio'), ('caio', 1.0)]


If you want a list of list,

list(map(list, zip(list1, list1[1:])))
# Result
[['hi', 'hello'], ['hello', 'goodbye'], ['goodbye', 'caio'], ['caio', 1.0]]
Answered By: Rahul K P

I like the solution proposed by @Rahul K P, but here is another option. List comprehension is always almost faster than a loop, so you can do it like this:

list1 = ['hi', 'hello', 'goodbye', 'caio', 1.0]
newList1 = [list1[i:i+2] for i in range(len(list1)-1)]

I would appreciate if you test all 3 solutions and share the results.

Answered By: Boris Silantev
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.