0

I'm learning python and I was trying to write a function that checks whether the number 6 is within the first 4 items of a given list.

I was surprised that this code works:

def first3(list):
    for item in list[0:3]:
        if item == 6:
            return True
    return False

print(first3([1, 2, 6, 3, 4])) # True
print(first3([1, 2, 3, 4, 6])) # False
print(first3([1, 2, 3, 4, 5])) # False
print(first3([1,2,6,3,0,0])) # True
print(first3([1,2,3,3,0,6])) # False
print(first3([6])) # True
print(first3([])) # False

I expected an out of range error for lists with less than 4 items. (EDIT: I was mistaken - has nothing to do with inside or outside the function)I tried around and found out, that outside of a function definition, there will be an out of range error.

This must be a super basic question but I didn't mange to get the google query right for an answer. Can anyone shed some light on how this is handled?

I'm using Python 3.9.2 if that matters.

Thanks a lot!

  • What does that mean, *"outside of a function definition, there will be an out of range error"*? Where exactly did you expect or experience such an error? – deceze Mar 26 '21 at 07:41
  • Does this answer your question? [Why does substring slicing with index out of range work?](https://stackoverflow.com/questions/9490058/why-does-substring-slicing-with-index-out-of-range-work) – ScootCork Mar 26 '21 at 07:42
  • and just to mention not to use `list` as name - it's a built-in function. – buran Mar 26 '21 at 07:44
  • " I tried around and found out, that outside of a function definition, there will be an out of range error." no? Outside of a function definition, there won't be an error... – juanpa.arrivillaga Mar 26 '21 at 07:46
  • Yes, I think I understood! Slicing out of index is allowed and just returns what there is to return. Referencing out of index will return "IndexError: list index out of range" – Alexander Ladda Mar 26 '21 at 07:48

0 Answers0