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.
Answers:
This would get what you want:
n = int(input())
list1 = [
int(input()) for _ in range(n)
]
print(list1)
As map doc described:
Return an iterator that applies function to every item of iterable, yielding the results.
The mistakes as follows:
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.
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())
.
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.
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.
This would get what you want:
n = int(input())
list1 = [
int(input()) for _ in range(n)
]
print(list1)
As map doc described:
Return an iterator that applies function to every item of iterable, yielding the results.
The mistakes as follows:
input()
function get astring
from your console standard input. And,string
is an iterable type! So,list(map(int, "23"))
will return a[2,3]
list.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())
.
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.