What does the following line mean in Python: list (map (int, input().strip().split())) [:i]?

What does the following line mean in Python: list (map (int, input().strip().split())) [:i]?

This is python one liner. I encounter this in Hackerrank Python Practice problem ( Find the Runner-Up ). Let me break this statement into multiple parts so that you can understand word by word or keyword.

So we have statement as - list (map (int, input().strip().split())) [:i]

input()

This is used to fetch input from the user. In this case. We are expecting the user to provide a list of integers.

input().strip()

strip() will remove spaces at the beginning and at the end of the string. Why is it needed? Because some users will do that and that might break your program.

input.strip().split()

This will split a string into a list where each word is a list item.

map(int, input().strip().split())

map() takes two arguments. The first one is the method to apply, the second one is the data to apply it to. By this understanding, we can see this is doing nothing but typecasting every element of the list to an integer value. Since map returns the data type it was applied to, the list() method applied over map() is redundant.

list(map(int, input().strip().split()))[:i]

It takes the list we have obtained and returns only the first "i" elements.

Lets say i have a list “num” which has all the elements non-integer and i want to convert all the elements to integer.

num=[1.5,2.66,33.77,4.909]

to do that we need to apply int() function on all the elements such that

[int(1.5),int(2.66),int(33.77),int(4.909)]

to perform above operation we can use map function.

num2 = list(map(int,num))

num2

[1, 2, 33, 4]

map applies int() finction on each element of list “num” and returns iterator object which if required can be converted to list eg:”num2″

Then slice a list Eg.

list(map(int,input().strip().split()))[:2]

5 7 8 10 12 ( space seperated user input)

[5, 7] sliced list i.e 2 elements starting from index 0 in the list ,[0:2]