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!