2

Hello I am having a struggle with creating a python list. I have list of numbers and i want to create list of pairs so that pair is also list and it looks like this: [[x0, x1], [x1, x2], ...]. I have tried list comprehension but its very slow for long lists.

Can anyone suggest a better (faster) solution?

example:

input = [0.74, 0.72, 0.63, 0.85, 0.75, 0.64] of length 6
output = [[0.74, 0.72], [0.72, 0.63], [0.63, 0.85], [0.85, 0.75], [0.75, 0.64]] of length 5

what i have tried:

output = [[x, y] for x, y in zip(input[0:len(input)-1], input[1:len(input)])]

Thanks in advance!!

ondrados
  • 272
  • 3
  • 9

2 Answers2

3

For large array lengths, use NumPy:

import numpy as np

input = [i for i in range(5000)]
np_input = np.array(input)

%timeit output = [[x, y] for x, y in zip(input[0:len(input)-1], input[1:len(input)])]
# 949 µs ± 35.9 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)

%timeit output = np.array([np_input[:-1], np_input[1:]]).reshape(-1, 2)
# 11.5 µs ± 873 ns per loop (mean ± std. dev. of 7 runs, 100000 loops each)

# Answer suggested by @Maryam
%timeit output = np.concatenate((np_input[:-1].reshape(-1,1), np_input[1:].reshape(-1,1)), axis=1)
# 21.9 µs ± 1.17 µs per loop (mean ± std. dev. of 7 runs, 10000 loops each)

You can see output = np.array([np_input[:-1], np_input[1:]]).reshape(-1, 2) is fastest.

For smaller arrays, use your's method with some changes:

input = [0.74, 0.72, 0.63, 0.85, 0.75, 0.64]

%timeit output = [[x, y] for x, y in zip(input[0:len(input)-1], input[1:len(input)])]
# 2.29 µs ± 46.3 ns per loop (mean ± std. dev. of 7 runs, 100000 loops each)

%timeit output = [[x, y] for x, y in zip(input[0:], input[1:])]
# 1.92 µs ± 19.8 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)
Rahul Vishwakarma
  • 1,446
  • 2
  • 7
  • 22
0

Maybe working with numpy has better performance for your large list:

import numpy as np

input = np.array([0.74, 0.72, 0.63, 0.85, 0.75, 0.64])
output = np.concatenate((input[:-1].reshape(-1,1),
                         input[1:].reshape(-1,1)),
                         axis=1)

The output is as follows:

array([[0.74, 0.72],
       [0.72, 0.63],
       [0.63, 0.85],
       [0.85, 0.75],
       [0.75, 0.64]])
Qasem Nick
  • 127
  • 1
  • 2
  • 12
Maryam
  • 660
  • 6
  • 19