Home > other >  Using identical 'for' loop and 'all()' function yield different results
Using identical 'for' loop and 'all()' function yield different results

Time:04-12

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?

CodePudding user response:

You're overthinking this.

As the error message states, all() expects an iterable, like a list or a tuple. You are making a single comparison between two integers, so there's nothing to iterate over.

To resolve, change the for loop to return False if we see a pair of elements that violates the sorted constraint. If our iteration doesn't find any violations, return True. This mimics the actual behavior of all():

def is_sorted(mylist):
    for i in range(len(mylist)-1):
        if mylist[i] > mylist[i 1]:
            return False
    return True
  • Related