Lets say that I want to create a list of names
listOfNames = []
Then I have a while loop such as
count = 0
while listOfNames[count] < 10:
nameList[count] = raw_input("Enter a name: ")
count += 1
Python says that the list index is out of range, but the list index should be at 0, correct?
How do add to the list each time the while loop is ran? I'm assuming something is wrong with my list assignment.
An empty list doesn't have any index yet, it's an empty list! If you want to fill it, you have to do something like this :
while count < 10:
nameList.append(raw_input("Enter a name: "))
count += 1
This way, your condition will be evaluated and with the append method, you will be able to add new items in your list.
There are a few advanced tricks to do this easily, but considering your level, I think it's better that you understand this code before moving on.
Most idiomatic is to use a list comprehension:
namelist = [raw_input("Enter a name: ") for i in range(10)]
(or use _
for i
, although I personally wouldn't)
This has the advantage of creating the list on the fly, while having to use neither the append() method nor explicit indexing.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With