issue while understanding the map and input function python

Question:

i am trying to take a list from user input using below code

n=int(input())
list1=[]
for i in range(0,n):
   ele=list(map(int,input()))
   list1.append(ele)
print(list1)

as per my understanding for below input 3 23 23 33
this should give me [23,23,33], however I am getting [[2,3],[2,3],[3,3]]
can anyone please help understanding the flow and working of the map and list function and what I am missing.

Asked By: Devesh Joshi

||

Answers:

This would get what you want:

n = int(input())
list1 = [
    int(input()) for _ in range(n)
]
print(list1)
Answered By: Waket Zheng

As map doc described:

Return an iterator that applies function to every item of iterable, yielding the results.

The mistakes as follows:

  1. input() function get a string from your console standard input. And, string is an iterable type! So, list(map(int, "23")) will return a [2,3] list.
  2. list1.append(list2) will get a nested list like [[2,3]].

To get your wished result, you may change ele=list(map(int,input())) to ele=int(input()).

Answered By: Doors

thanks! understand the working now as the below
input() function get a string from your console standard input. And, the string is an iterable type! So, list(map(int, "23")) will return a [2,3] list.

Answered By: Devesh Joshi
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.