-2

If I run the code from the commented #c_list, it works. But if I run it from the a_list that takes input, I get an empty list. How do I solve it?

a_list =  [input('Enter input for list: ')]
#c_list = [10,20,24,25,26]
length = len(a_list)

if length>3:
    b_list = a_list[2:length-2]
    print(b_list)
else:
    print("Not Possible")
martineau
  • 119,623
  • 25
  • 170
  • 301
Irrelevant
  • 43
  • 6
  • 9
    `input()` will always return a _single string_. It looks like you're trying to get multiple elements out of it. Have you tried `input(...).split(',')` instead of `[input(...)]`? – Green Cloak Guy Jul 26 '21 at 20:09
  • 3
    Your question doesn’t match your title, what exactly are you asking about? – Sayse Jul 26 '21 at 20:13
  • when i submit a list through input,I get the else condition,but if I use normal list,the code works ok. – Irrelevant Jul 26 '21 at 20:15
  • 2
    @Irrelevant You can't "submit a list through input". All you can do is read a string that the user enters. What you do with that string is up to you. How are you entering your values? Are you separating them with spaces? If so, then you can use `.split()` to split it into a list of strings. Do you want the values to be read as integers? Then you need to use `int` to convert them. – Tom Karzes Jul 26 '21 at 20:19
  • @TomKarzes oh! I want them to be read as integers.But using int as int(input("Enter input for list: ))gives error – Irrelevant Jul 26 '21 at 20:25
  • @Irrelevant Right. You first need to split the values into a list of strings, *then* convert the individual strings into integers. – Tom Karzes Jul 26 '21 at 20:27
  • [Get a list of numbers as input from the user](https://stackoverflow.com/q/4663306/15497888) may be helpful. – Henry Ecker Jul 26 '21 at 20:36

1 Answers1

1

As Green Cloak Guy mentioned, input() always returns a single string.

In Python 3.x, if you want multiple inputs you can use the .split() method and a list comprehension:

input_list = [int(x) for x in input("Enter values for list: ").split()]

#Enter values for list: 1 2 3 4 5

input_list
Out[4]: [1, 2, 3, 4, 5]

Keep in mind this will only work for integer values, if you want the user to input float values as well, you can change int(x) to float(x). Only caveat is that the integer values will also be cast to float values:

input_list = [float(x) for x in input("Enter values for list: ").split()]

#Enter values for list: 1 2 3.3 4 5

input_list
Out[8]: [1.0, 2.0, 3.3, 4.0, 5.0]

More on the .split() method here

More on list comprehensions here

kylepina1
  • 26
  • 4