开发者

List index out of range

I have written a program that makes sure each cookie has more than 5 chips before moving on. However, the line if cookie[i] > 5: seems to be problematic, as it produces a "list index out of range" error. I thought foo = [] created a list with no ending, so I don't get why any number would be out of range in this list. What am I doing wrong?

cookie = []

...

for i in range(0, 11):
    if cooki开发者_开发知识库e[i] > 5:
         break


Try:

len(cookie)

You'll see if you haven't put anything in it that it'll be size 0. With cookie = [] you can continuously add elements to the list but it's initialized empty.


How about:

cookies = []

...

for cookie in cookies:
    if cookie > 5:
         break


You can't really have a list with no ending that in your case presumably has only zeros in it.

You can however create a list with 11 zeros:

cookies = [0] * 11

Or create something that returns 0 if you access it at an index if you haven't put anything else in there:

import collections
cookies = collections.defaultdict(int)

Note that this is not a list but a map.


cookie = [] creates empty list with no data, so no indexes here. You need to fill cookie with some data first (e.g. using cookie.append(some_data)).


foo=[] does not create a list with no ending. Instead, it creates an empty list.

You could do

for i in range(0, len(foo)):
    if(cookie[i]>5):
        break

Or you could do

for c in cookie:
    if c>5:
        break


foo = [] creates an empty list, not a list with no ending. Any index access will fail on an empty list. To check the length of a list, use len(mylist). The length of an empty list is 0, and indices are zero-based. So:

cookie = []
len(cookie) == 0
cookie[0] ## will raise IndexError

cookie.append('something')
len(cookie) == 1
cookie[0] ## will return 'something'

See the list docs

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜