PeterPefi
PeterPefi

Reputation: 99

Python - List index out of range, "for" loop

I don't get how a "for" loop that iterates through the elements of a list can be out of range. First part seems to be okay as I can print it.

import random

def random_list(n):
    l = []
    for i in range(0,n):
        l.append(random.randint(0,n))

    return l


def maximum(n):
    x = 0
    b = random_list(n)
    for i in b:
        if b[i] > x:
            x = b[i]


print (maximum(10))

Upvotes: 1

Views: 242

Answers (2)

Susmit Agrawal
Susmit Agrawal

Reputation: 3764

Considering that you know how to iterate over a list in python, the error could be due to randint, which generates an integer in the interval [low, high]. This means high is a possible output, while the highest index in your program is high - 1.

For example,

random.randint(0, 0)

gives 0.

Similarly, random.randint(10) can return 10.

If you don't understand how to iterate over a list in Python, consider a simple example:

Take the list below:

myList = [1, 3, 5, 7, 9]

Now, there are two ways to iterate over the list:

  1. Directly accessing elements:

    for element in myList:
        print(element, end=" ")
    

This gives the output:

1 3 5 7 9
  1. Accessing elements using indices

    for idx in range(len(myList)):
        print(idx, ":", myList[idx], end=" ")
    

This gives the output:

0:1 1:3 2:5 3:7 4:9

Upvotes: 0

iz_
iz_

Reputation: 16633

This:

for i in b:
    if b[i] > x:
        x = b[i]

Iterates over the elements of b, not the indices. Change it to

for i in b:
    if i > x:
        x = i

You also need to return something from your function, probably x.

Upvotes: 3

Related Questions