adus
adus

Reputation: 79

Index out of range error when comparing values

a=[8,24,3,20,1,17]
r=[]
for i in a:
    for j in a:
        s=a[i]-a[j]
        r.append(s)
print r

When I run this program Why the index out of range error for this question?

Upvotes: 0

Views: 52

Answers (5)

Sash Sinha
Sash Sinha

Reputation: 22418

Use s = i - j instead of s = a[i] - a[j]:

a=[8,24,3,20,1,17]
r=[]
for i in a:
    for j in a:
        s = i - j
        r.append(s)
print r

Output:

[0, -16, 5, -12, 7, -9, 16, 0, 21, 4, 23, 7, -5, -21, 0, -17, 2, -14, 12, -4, 17, 0, 19, 3, -7, -23, -2, -19, 0, -16, 9, -7, 14, -3, 16, 0]

Try it here!

Upvotes: 2

Safirah
Safirah

Reputation: 375

Maybe it's because when you do

`for i in list:`

i is not an index, but the actual number.

Try doing

a=[8,24,3,20,1,17]
r=[]
for i, x in enumerate(a):
    for j, y in enumerate(a):
        s = a[i]-a[j]
        r.append(s)
print r

or

a=[8,24,3,20,1,17]
r=[]
for i in range(len(a)):
    for j in range(len(a)):
        s = a[i]-a[j]
        r.append(s)
print r

Upvotes: 0

lucasnadalutti
lucasnadalutti

Reputation: 5948

i and j are values, and you are mistaking them for indices.

i and j start as 8 (your list's first element). Naturally, a[8] gives you an error since your list's size is lower than this.

Upvotes: 0

OneCricketeer
OneCricketeer

Reputation: 191874

i and j are already elements from your lists. No need to index a.

So, instead use s = i-j


Your issue is that a[i] becomes a[8] at the first iteration, which is out of bounds

Upvotes: 0

Fernando
Fernando

Reputation: 7905

You are iterating the values, you should do

for i in range(len(a)):

Upvotes: 0

Related Questions