awesomeguy
awesomeguy

Reputation: 290

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 cookie[i] > 5:
         break

Upvotes: 2

Views: 9964

Answers (6)

Rob Cowie
Rob Cowie

Reputation: 22619

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

Upvotes: 1

Otto Allmendinger
Otto Allmendinger

Reputation: 28268

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.

Upvotes: 2

Ravi
Ravi

Reputation: 3756

How about:

cookies = []

...

for cookie in cookies:
    if cookie > 5:
         break

Upvotes: 2

silent1mezzo
silent1mezzo

Reputation: 2932

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.

Upvotes: 5

Jack Edmonds
Jack Edmonds

Reputation: 33171

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

Upvotes: 1

Roman Bodnarchuk
Roman Bodnarchuk

Reputation: 29727

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)).

Upvotes: 1

Related Questions