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
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]
.
It is a "pythonic" way of creating a list
of int
s 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]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With