Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Creating an empty list to have data assigned afterwards

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.

like image 744
Hypergiant Avatar asked Nov 15 '10 14:11

Hypergiant


2 Answers

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.

like image 128
Vincent Savard Avatar answered Sep 30 '22 12:09

Vincent Savard


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.

like image 31
Andrew Jaffe Avatar answered Sep 30 '22 11:09

Andrew Jaffe