Click here to Skip to main content
15,311,717 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I have been making this list
stdnt = [['harry',24],['sandy',23],['mando',25]]
and want to take number of lists a as user input as mentioned in code below but compiler is throwing error, can you please tell me why I am wrong?

What I have tried:

   for _ in range(int(input())):
       a[0] = input()
       a[1] = float(input())
Updated 9-Oct-21 11:18am

1 solution

You define the array a as an empty array (a = []), then try to assign a value to a[0], which does not exist yet, so the program dies with a "list assignment index out of range" error". You can either create the array with two values to start, e.g.
a = [None, None]
or use append in the for loop e.g.
for _ in range(int(input())):
    a = []

Since input() accepts a prompt as an argument, why not use it? e.g. input('How many items to add? ") This would make it clear to anyone running the program what data is expected, rather than just a blank terminal screen. It's not known then if the program is busy, or waiting for input. But maybe you already do that, and the above snippet was just to illustrate the issue you're currently trying to resolve?
ABDEALI ATTARWALA 10-Oct-21 1:00am
Thank you, It helped a lot.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900