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.
CodePudding user response:
This would get what you want:
n = int(input())
list1 = [
int(input()) for _ in range(n)
]
print(list1)
CodePudding user response:
Map returns an iterator that applies function to every item of iterable, yielding the results
n=int(input())
list1=[]
for i in range(0,n):
ele=list(map(int,input()))
print(ele) # new print added to demonstrate
list1.append(ele)
print(list1)
#output
1 # If I give only 1 output, no matter how big or small the number is, It will be broken into digits
12345
[1, 2, 3, 4, 5] # first print inside the loop
[[1, 2, 3, 4, 5]] # second print outside the loop
here is the link for the official document
https://docs.python.org/3/library/functions.html#map
Input()
function takes argument as a string.
String is an iterable so, int()
function will be applied to each element of the string.
CodePudding user response:
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())
.