0
how to take input of a list in python
I want to take input as a list which the user will enter in format - [23, 45, 76]. if taking input it is including '[]' and ',' also. please tell me how to do it.
13 Respuestas
+ 6
Shaurya Kushwaha ,
for now, the best thing to do is to solve the task step be step.
the basic way would be:
(1) remove the brackets *[]*.
(2) split the result from step 1 by using *,* as separator.
the result of split will be a *list of string numbers*.
(3) iterate through the list and convert the *string numbers* to real integers.
for output use a new list.
+ 5
For string input you need to add input () function, where for integer inputs, you need to assign "int(input ())"
When you get "input" prompt box, you will be able to enter those numbers.
Re-learn input() lesson again.
+ 5
Shaurya Kushwaha ,
plaese show us your attempt by linking it here.
+ 5
Bob_Li , Mahmoud Akare ,
2 points to consider:
(1) the input format is defined as *[23, 45, 76]*, and should include brackets and comma.
using this input both codes do not work as expected.
(2) it is not seen as a helpful behavior when we are going to post a code, as long as the op has not shown his attempt here.
it is helpful to give hints and tips, so that the op has a chance to find a solution by himself.
+ 1
https://www.sololearn.com/compiler-playground/cN9Bf0tjFMm0
when giving input -
[13, 45, 78]
gives output -
['[13,', '45,', '78]']
but I want it to be -
[13, 45, 78]
+ 1
To be more explicit here, input() in python is always a string, and nothing can be done about that. int() *converts it* to an integer (if possible, and with limitations), but only after taking the input as a string. So what you need to do here is reformat and parse the input string into a list, eg with .split()
+ 1
Shaurya Kushwaha
npt = input()
# user input: 13 45 78
strs = npt.split(' ')
# strs = ['13', '45', '78']
nums = [int(x) for x in strs]
print(nums)
#[13, 45, 78]
one step:
nums = [int(x) for x in input().split(' ')]
+ 1
if I am taking 2d array -
[[1, 0, 0, 0, 1, 0], [1, 0, 1, 1, 0, 0], [0, 0, 1, 0, 0, 1], [1, 0, 1, 0, 0, 1], [1, 0, 1, 1, 0, 0]]
my code -
m = input()
m = m.replace('[', "")
m = m.replace(']', "")
n = list(map(int,m.split(",")))
print(n)
gives - [1, 0, 0, 0, 1, 0, 1, 0, 1, 1, 0, 0, 0, 0, 1, 0, 0, 1, 1, 0, 1, 0, 0, 1, 1, 0, 1, 1, 0, 0]
how to make it 2d array
0
Yes Lothar I didn't wanted list of strings but the other one.
0
lis = []
npt = input("Enter the number : ")
for i in npt:
if i != " ":
i = int(i)
lis.append(i)
print(lis)
You can fill in any number, even without commas or spaces
0
In one line
lis = [int(x) for x in input() if x != ' ']
print(lis)
0
probably easiest to split("],[") first and iterate through that list of lists, but you could also work through that final list in 6-entry-long chunks using something like slice if you prefer
0
X=list(int(input()))