+ 1
A better way to initialize a list?
For example, this piece of code gets 6 inputs and stores them in a list: inputList = [input(), input(), input(), input(), input(), input()] The code works as intended but what if I want to convert the values to integers like this: inputList = [int(input()), int(input()), ...] As you see it gets messy pretty quickly, so how would you initialize it? I tried this: inputList = [int(input())] * 6 but it somehow stores only the first value in all 6 indexes
12 Answers
+ 9
You asked for getting multiple inputs in an elegant way.
The elegant way is either using a string and splitting it or using a loop.
[input()] * 6 does not work as we only get one input and store it at multiple places.
Personally, I would use a list comprehension
inp = [int(input()) for n in range(6))]
However, beginners may find loops more readable.
+ 5
1. Let the user enter all integers separated by a blank space, in 1 line as string
2. Split the string by the separator, here blank space. You get a list of strings
3. Convert each element of the list to integer.
+ 4
You can use a loop.
+ 4
Yes, I found it now.
1. Create an empty list.
2. Get input inside of a for-loop
3. Convert input to int and append to list.
+ 3
When you need to store Input like this and it's more than 3, honestly just use one input and use some delimeters like comma, space, etc to identify a single value. That's how a professional code would've been written .. something like this
inputList = input ()
// Expected 1,2,3,a,4,6
Split by "," and check if every item meets the requirements of being an integer. There's no performance lost noticed and could be faster than loop in some cases. That's what Machine learner uses to accepts inputs
The other case is to just use a while loop if input is likely to be more than 3 but you didn't asked for this
+ 2
Agreed with Wong. Perhaps replacing the statements that after the 'for' statement to reduce confusion.
val = input()
item = int(val)
inp.append(item)
As Wong's suggested comprehensive code is not actually utilizing the 'n' variable.
+ 1
Thanks for replying but the problem is that I need to get 6 different inputs from the user(pop, snap, crackle - code coach).
Also isn't there a elegant way to get a specific or nonspecific amount of values?
+ 1
Lisa’s answer is great but need to elaborate more for learner to understand.
Code provided:
inp = [int(input()) for n in range(6)]
In plain English, it says:
1. inp is a list;
2. The element inside the list inp is int(input()), a.k.a. an input converted into integer;
3. And the element is looped for 6 times
A beginner version code would look like this:
inp = []
for n in range(6):
n = input()
n = int(n)
inp.append(n)
0
Pop,snap,crackle - code coach
0
Not really what I asked for but thanks anyway
0
Your list comprehension method is exactly what I wanted, thank you