-2

lets say we have an array:

arr1 = [1,2,3,4,5]

& I want to print all pairs of 3 values from this list in the order it is: for ex, this is the output i want from the array above

output:

[1,2,3]
[2,3,4]
[3,4,5]

how can i achieve this in the simplest way possible without using libraries.

  • 1
    Use `[A[i : i + size] for i in range(0, len(A), step)]` with size = 3 and step = 1. If you don't want the trailing incomplete sublists, you can stop the iteration sooner. Change `len(A)` to `len(A) - size + 1` – cs95 Dec 20 '20 at 22:21

1 Answers1

0

You can use list slicing:

arr1 = [1, 2, 3, 4, 5]

for x in range(3):
    print(arr1[x:x + 3])

Out:

[1, 2, 3]
[2, 3, 4]
[3, 4, 5]
Maurice Meyer
  • 17,279
  • 4
  • 30
  • 47