开发者

Creating an empty list to have data assigned afterwards

Lets say that I wan开发者_开发技巧t 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.


count = 0
while listOfNames[count] < 10:
    nameList.append(raw_input("Enter a name: "))
    count += 1

Use append for quick n easy...

Alternatively:

nameList[len(nameList):] = [raw_input("Enter a name: ")]

Edit: Did you mean listOfNames to be appended as opposed to nameList?


Your list assignment is right, your problem is with your use of indexes which do not yet exist.

    count = 0
while listOfNames[count] < 10:
    nameList[count] = raw_input("Enter a name: ")
    count += 1

I'm fairly sure this code doesn't do what you intend. What this code is doing is checking the first through tenth elements of listOfNames for a number which is less than 10, but since its an empty list there is no element with index 0, or any other index for that matter hence your list index out of range exceptions.

The following will work as you intend:

count = 0
while len(listOfNames) < 10:     # Keep going until the list has 10 elements
    nameList.append(raw_input("Enter a name: "))
    count += 1

However I'd suggest using the following which does exactly the same thing but should be more efficient as well as being more aesthetically pleasing:

for _ in range(10):
    listOfNames.append(raw_input("Enter a name:"))

Note the use of append instead of an index reference. This will add the new element on to the end of the list whereas using the index as you were trying to do will fail since to assign to and index there has to be an element present in the first place.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜