Python help, lists

I am having trouble inputting data into a list with unknown amount. Also afterwards, I need to be able to then reprint the list in reverse while not using the reverse function.
Thank You

lengthOfList=(int(input(‘How many numbers do you want to list(1-10)?:’)))

myList=list(range(0,lengthOfList))

for INDEX in range (0,lengthOfList,1):
print(‘Enter number ‘, myList[INDEX]+1,’:’)

Just a note: please make sure you’re adding posts to the right category (this is not the first one I’ve had to change from CD-Media -> Photos). :slight_smile:

4 Likes

Could you please elaborate on that?

If I’m understanding your question correctly I think you want to be able to add numbers to a list regardless of its size? Lists in python don’t have a fixed size so you can just initialize it like this:

list = []

and then add items to the list like this:

list.append(var)

Thank you.

How do you input numbers for an unknown amount of times? I created the question “How many numbers do you want to enter?” The user can type in any number from 1-10. If the user types 3 for example, I need it to ask “Enter your first number:” Then “Enter your second number:” etc. I then want to use those numbers to come up with a sum, average, etc. So, I need each inputted number assigned a unique variable (I assume). I will not know ahead of time how many variables I will need. I am using the list function too [ ].

You are on the right track using range.

inputs = []
n = 3
for i in range(n):
    inputs.append(input(f'Enter input {i}: '))
print(inputs)

Try it and see what happens.

For fun, a one liner: inputs = list(map(lambda i: input(f'Enter input {i}: '), range(3)))

alternatively [input(f'Enter input {i}: ') for i in range(3)], but this probably isn’t immediately intuitive to a beginner

OP: I recommend Corey Schafer’s Python guides, as well as r/learnpython

1 Like

Or just keep read numbers with “input()” until the user inputs a blank string:

while True:
    value = input("Enter a number (enter to quit): ")
    if not value.strip():
        break
    # rest of your code

An equivalent and more intuitive line is if value.strip() == "":

Thank you.
This is what my instructor replied:

myList = [ ]

then append to it in a loop that happens as many times as the user wants to

times = int(input(‘how many times’))

for i in range(0, times, 1 )

ask user to enter a value

myList.append( … ) # append the value to the list

Now I am more lost…

You already know how to ask the user for the number of inputs. Can you reuse that line of code to ask for the inputs themselves?

Just a quick meta-question: this isn’t homework, is it? Some people don’t take kindly to (unknowingly) helping with homework, and the question sounds like something that might be set as homework.

This topic was automatically closed 365 days after the last reply. New replies are no longer allowed.