# Create subList of list, with increased performance

## Question:

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?

Thanks.

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)]

Edit

If you want a list of list,

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

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.

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.