1

n is the total number of Input our array needs. As the goal is to print the pair of numbers which is taken as input. I wanted to find the output of this 3rd line mention below and as i hit enter in python ide, I got this result.
I am a bit confused that how this 3rd line in the code works. As i am learning new things daily this problem came ahead and i was struck on 3rd line.

n = int(input())
arr = list(map(int, input().split()))
arr = [arr[i:i+2] for i in range(0, n*2, 2)]
print(arr)

1st input -

4    
1 3 2 4 6 8 9 10   

2nd input -

4    
6 8 1 9 2 4 4 7

1st Output -

[[1, 3], [2, 4], [6, 8], [9, 10]]  

2nd Output -

[[6, 8], [1, 9], [2, 4], [4, 7]]
Martin
  • 209
  • 3
  • 10
  • P.s. I am not able to find "arr[i:i+2]" related information anywhere, but thanks for this awesome platform. – Martin Sep 24 '20 at 20:34

2 Answers2

1

arr = [arr[i:i+2] for i in range(0, n*2, 2)] is equivalent to:

arr2 = []
for i in range(0, n*2, 2):
    arr2.append(arr[i:i+2])
arr = arr2

range(0, n*2, 2) is an iterator that yields every other number from 0 up to (but not including) n*2.

arr[i:i+2] slices arr, taking elements from the ith position up to (but not including) the i+2th position.

So, this expression effectively gives you [arr[0,2], arr[2,4], arr[4,6], ..., arr[n*2-2,n*2]].

0x5453
  • 12,753
  • 1
  • 32
  • 61
  • I just tried replacing the loop you provided with the one in the question, but it didn't give the same result –  Sep 24 '20 at 20:27
  • Thanks, Your answer helped me and I have understood the statement now. Thanks for helping. – Martin Sep 24 '20 at 20:31
  • @Cool_Cornflakes Whoops, forgot `arr = arr2`. Should match exactly now. – 0x5453 Sep 24 '20 at 21:02
1

A good technique for understanding one-liners like this is to expand the one-liner one step at a time.

Consider consider this input:

n = 4
arr = [6, 8, 1, 9, 2, 4, 4, 7]

Let's start with the original line 3.

arr = [arr[i:i+2] for i in range(0, n*2, 2)]

First of all, range(0, n*2, 2) is range(0, 8, 2) which functions like the list [0, 2, 4, 6]. So now we're working with this:

arr = [arr[i:i+2] for i in [0, 2, 4, 6]]

Note that arr[i:i+2] refers to the two-element array [arr[i], arr[i+1]]. For example, when i=0, arr[i:i+2] = [arr[0], arr[1]] = [6, 8]. So now we have:

arr = [[arr[i], arr[i+1]] for i in [0, 2, 4, 6]]

Expanding this out for each i gives:

arr = [[arr[0], arr[1]], [arr[2], arr[3]], [arr[4], arr[5]], [arr[6], arr[7]]]

Substituting in the values for arr gives the final result:

[[6, 8], [1, 9], [2, 4], [4, 7]]
Cam
  • 14,930
  • 16
  • 77
  • 128
  • Thanks, I understood it now. I am not getting "arr[i:i+2]" part, but you have explained it good. kudos to you. – Martin Sep 24 '20 at 20:30
  • @Martin happy to help! Does https://stackoverflow.com/questions/509211/understanding-slice-notation help clarify the `arr[i:i+2]` syntax? – Cam Sep 24 '20 at 20:53