Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can anyone explain me what this Python 3 command do?

I am a beginner in Python programming. I have checked what the methods does separately, but not getting as a whole. Here is a program was written as a answer for the problem: Write a program to print all elements of an array in reverse order:

if __name__ == '__main__':                          #1   
    n = int(input())                                #2
                                                    #3
    arr = list(map(int, input().rstrip().split()))  #4
    for i in range(n):                              #5
        print(arr[-i-1],end=' ')                    #6

I am not getting line 4. Can anyone explain step by step what that line is doing? How they are working and giving the output as a whole? The inputs were separated by space:

5            #length of the array
1 2 3 4 5     #inputs separated by space
like image 262
LordOfThunder Avatar asked Sep 02 '18 08:09

LordOfThunder


2 Answers

input() looks like it gets the next line of input. From the example this is the string "1 2 3 4 5\n" (it has a newline on the end).

rstrip() then removes whitespace at the right end of the input, including the newline.

split() with no arguments splits on whitespace, transforming the input to an iterable of strings. e.g. ['1', '2', '3', '4', '5']

map(int, sequence) applies int to each string. e.g. int('1') -> 1, int('2') -> 2 etc.. So your sequence of strings is now a sequence of integers.

Finally list(seq) transforms the sequence to a list type. So now you have [1,2,3,4,5].

like image 83
Hitobat Avatar answered Oct 08 '22 23:10

Hitobat


It is a "pythonic" way of creating a list of ints from a space seperated numeric input:

arr = list(map(int, input().rstrip().split())) 

It takes makes a list out of the result of map(...) which returns a generator.

map takes a function and applies it to all elements of the second argument iterable.

input().
rstrip().
split() takes an input, removes all whitespaces on the right side and splits it into parts on whitespaces which is then fed as iterable into map(int, ...) which creates a generator result from applying int to all elements of the given iterable. The result of map is fed into list(...) which makes a list from it.

"1 2 3 4" => ["1","2","3","4"] -> generator (1,2,3,4) -> [1,2,3,4]
like image 25
Patrick Artner Avatar answered Oct 09 '22 00:10

Patrick Artner