1

I'm trying to sort a list in order from odd to even but when I pass it through and assert statements it only works on a few assert statements. Looking at the print output everything should be working as its in the right order from odd to even but its failing the assert statements.

 def oddsBeforeEvens(theList):
    odd = []
    even = []
    for x in theList:
        if x % 2 == 0:
            even.append(x)
        else: 
            odd.append(x)
    theList = odd + even


aList = [-1, 0, 1, 2, 3, 4, 5, -6, -7]
oddsBeforeEvens(aList)
print(aList)  # Debugging print
assert(aList[0] % 2 != 0)  # odd integer
assert(aList[1] % 2 != 0)
assert(aList[2] % 2 != 0)
assert(aList[3] % 2 != 0)
assert(aList[4] % 2 != 0)  # odd integer
assert(aList[5] % 2 == 0)  # even integer
assert(aList[6] % 2 == 0)
assert(aList[7] % 2 == 0)
assert(aList[8] % 2 == 0)  # even integer
Daniel Walker
  • 6,380
  • 5
  • 22
  • 45
Connor1719
  • 19
  • 2
  • 3
    Your function doesn't actually modify the input. It only makes a local variable. The line with a "# Debugging print" comment should have made that obvious ... – wim Nov 17 '20 at 02:59

2 Answers2

2

Read this:

Any time you see varname =, you're creating a new name binding within the function's scope. Whatever value varname was bound to before is lost within this scope.

So when you did theList = odd + even inside oddsBeforeEvens it doesn't "pointing" to the global aList anymore, aList remains unchanged. You can fix it this way:

 def oddsBeforeEvens(theList):
    ...
    return odd + even

...
aList = oddsBeforeEvens(aList)
...
fas
  • 1,393
  • 10
  • 20
0

In your function, you assign a value to theList. Whenever you assign a value to a variable in a function, Python will assume that the variable is local to that function unless you explicitly state otherwise.

So, when you write

theList = odd + even

Python creates a variable local to that function called theList. The original theList variable reminds untouched. So, when you assert that aList[1] %2 != 0, that fails because that element is still 0.

It would be better to return the new list from the function like

def oddsBeforeEvens(theList):
    odd = []
    even = []
    for x in theList:
        if x%2 == 0:
            even.append(x)
        else:
            odd.append(x)
    return odd + even
Daniel Walker
  • 6,380
  • 5
  • 22
  • 45