1

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.

Ev0
  • 63
  • 5
  • Does this answer your question? [How do I split a list into equally-sized chunks?](https://stackoverflow.com/questions/312443/how-do-i-split-a-list-into-equally-sized-chunks) – Mechanic Pig Sep 17 '22 at 15:36

2 Answers2

2

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]]
Rahul K P
  • 15,740
  • 4
  • 35
  • 52
1

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.

Boris Silantev
  • 753
  • 3
  • 13
  • Both worked great! Thank you. Marking this as the answer as the result needs to be passed into a pandas DF and the other answer seems to confuse it despite it still being a list but looking like a tuple(). Not sure why – Ev0 Sep 18 '22 at 15:03