简体   繁体   中英

IndexError: index out of range: 5

So I am in an intro programming class and I have an assignment where I need to take in a list as a param, and then return a list with only the vals from the first list that are divisible by 6. The class uses Python and this is what I think should be working but I keep getting an error.

    def youAndThe6th(nums):
        numsNew =  []
        for x in nums:
            if nums[x]%6 ==0:
                numsNew.append(nums[x])
        return numsNew

And then when I run something like:

     youAndThe6th([1,2,3,4])

I get and error saying "IndexError: index out of range: 4". And the 4 is just 1 plus the last index. So I understand that it is trying to check and index that isn't in the list, I just don't see what about my code is trying to call past the last index of the given string.

Thanks!

First thing first python list are zero indexed that is they start from 0

Modified Code:

def youAndThe6th(nums):
    numsNew =  []
    for x in nums:
        if x%6 ==0:
            numsNew.append(x)
    return numsNew

Modified code with range:

def youAndThe6th(nums):
    numsNew =  []
    for x in range(len(nums)):
        if x%6 ==0:
            numsNew.append(x)
    return numsNew

or we could make things easier in my point of view using list comprehension

numsNew =[x for x in nums if x%6 == 0]

Notes:

  • When you loop through an list you are actually looping over it's content and not it's index you could use range if you want it's index
  • Your list has four elements values = [ 1 , 2 , 3 , 4] index = 0 , 1 , 2 , 3 So when you were iterating over the list you got the value 4 and you did nums[x] == nums[4] since the list has only index up to 3 it throw IndexError: index out of range: 4

Your problem is in line 4. Instead of

if nums[x]%6 == 0:

you ought to have

if x%6 == 0:

What's happening is that your for statement is already giving you the values stored in the list (as x). You're then trying to take the xth value of the list, and in your case, your list only has 4 values, so asking for value 4 is out of range (since python starts counting with 0).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM