-2

I need to create a list with a length determined by a user input.

How would I do this?

Example: If the user inputs 3 I need a list with 3 indexes.

4
  • 1
    Hint: You can append to a list to add extra elements.
    – Martijn Pieters
    Mar 23, 2015 at 19:11
  • 1
    what part is not clear? How to get an integer from a user? How to create a list of a given length (what content do you want to put in it e.g., how do you think a list of 3 items should look like)?
    – jfs
    Mar 23, 2015 at 19:13
  • Not very good at python yet. I just created an empty list and appended it with the inputs from the user. idk how to post the code or else I would show you. Thanks for the response. Mar 25, 2015 at 5:29
  • Something like this: D = [ ] while Days >= n: print("Enter the major event for day", n, ": ", end="") x = input( ) D.append(x) n = n + 1 Mar 25, 2015 at 5:32

2 Answers 2

9

What do you want to fill the list with? If you just want a list with n indexes:

n = user_input_length
list = [None for x in range(n)]
1
  • 2
    None is immutable (moreover it is a singletone); you could use your_list = [None] * n (don't use list as a name; it shadows the builtin).
    – jfs
    Mar 23, 2015 at 20:00
1

You can take in input, then populate your list:

import random
num = int(input('How long do you want the list? ')) #5
lst = [random.randint(1, 10) for i in range(num)]
print lst #[6, 1, 2, 1, 8]
4
  • 1
    there is no raw_input() in Python 3.
    – jfs
    Mar 23, 2015 at 20:00
  • Thank you. I ended up using the append function to do what I needed to do. Mar 25, 2015 at 5:29
  • How do you post your code in that grey box? Mar 25, 2015 at 5:31
  • @inlakechalakin you have to indent it four spaces
    – A.J. Uppal
    Mar 25, 2015 at 16:54

Not the answer you're looking for? Browse other questions tagged or ask your own question.