0

I am new to python, this is a basic question

How do you get a list of string as input from the user? I tried:

array = []
for i in range(0,4):
    array[i] = input("Enter string")

This has an error. I know I am wrong. How do we get a list of strings as input?

vba
  • 526
  • 8
  • 20

4 Answers4

2

Your array has size 0, this is why you can't access any elements (or assign to them). The correct code would be:

array = []
for i in range(4):
    array.append(input("Enter string"))
Dimitris Fasarakis Hilliard
  • 150,925
  • 31
  • 268
  • 253
Sekuraz
  • 548
  • 3
  • 15
2

Try this:

for i in range(4):
    array.append(input("Enter string >>"))

Since your array doesn't have any values yet, assigning to array[i] would not work.

Dimitris Fasarakis Hilliard
  • 150,925
  • 31
  • 268
  • 253
Jeremiah
  • 623
  • 6
  • 13
2

Concise:

array = [input("Enter string: ") for i in range(4)]
Spherical Cowboy
  • 565
  • 6
  • 14
  • 1
    Indeed this is elegant but in python 2x input() evaluates the string as a variable and throws a NameError. In python 2x I would recommend using raw_input() rather than input(). But since this question is tagged under python3x it's preferred :D – repzero Mar 22 '17 at 22:16
  • Thanks for noting this in case someone using Python 2 tries to use it. Links to the relevant entries in the Python 2 documentation: [input](https://docs.python.org/2/library/functions.html#input) & [raw_input](https://docs.python.org/2/library/functions.html#raw_input) – Spherical Cowboy Mar 22 '17 at 22:29
0

when range limit is unknown i.e., when (n) needs to be taken as an input from the user,

n = int(input("Enter the number of names in list for input:"))
a = [input() for i in range(n)]