Reputation: 113
i was trying to fill a list with inputs, but it gave me index out of range although the index is starting from zero, as far as i know we don't have to specify the length of a list in python.
inputs = input("Enter the number of inputs: ")
lists = []
k = 0
while k<inputs:
lists[k]= input()
k+=1
Upvotes: 0
Views: 59
Reputation: 53653
Another possibility: Initialize lists
as an empty list and then append the input with the +=
operand.
lists = []
k = 0
while k < inputs:
lists += [input()]
k+=1
Upvotes: 0
Reputation: 31682
You can initialize your list before using indexes of it:
lists = [0] * int(inputs)
And then you can use your code
Upvotes: 0
Reputation: 500733
Use list.append()
to add an element to the end of the list:
while k<inputs:
lists.append(input())
k+=1
or with a list comprehension:
lists = [input() for _ in range(inputs)]
Upvotes: 0
Reputation: 160587
Because you are creating an empty list with lists = []
and then accessing an element of this empty list. This is the cause of the IndexError
.
Appending with lists.append()
helps you avoid index errors like this one. You generally want to use indexing when accessing elements and not when populating the list.
Upvotes: 1