I'm learning Python and trying out a simple exercise: using a for loop to check if a list is in order, and creating a function for that.
So here's my code, which works well:
def is_sorted(mylist):
if all(mylist[i] <= mylist[i+1] for i in range(len(mylist)-1)):
return True
else:
return False
mylist = [2, 7, 5, 4, 4, 8, 3, 1]
is_sorted(mylist)
It returns False as it should be. I've tested a few other lists, and they all work well. But when I slightly modify the code, it no longer works:
def is_sorted(mylist):
for i in range(len(mylist)-1):
if all(mylist[i] <= mylist[i+1]):
return True
else:
return False
mylist = [2, 7, 5, 4, 4, 8, 3, 1]
is_sorted(mylist)
Here's the error code:
/var/folders/xxxxx.py in is_sorted(mylist)
1 def is_sorted(mylist):
2 for i in range(len(mylist)-1):
----> 3 if all(mylist[i] <= mylist[i+1]):
4 return True
5 else:
TypeError: 'bool' object is not iterable
It looks to me that the two snippets are identical. I'm not sure why the second one doesn't work. What have I missed?