1

i have written a function that produces a tuple of two lists from one list. one list contains the second, fourth and fifth values and the other list contains all the remaining values. i also have a condition that if reverse=True the values of the lists will be reversed when returned.

def seperate(x, reverse=False):

    xs = []
    ys = []
    for i in range(0, len(x), 2):
            xs.append(x[i])
            ys.append(x[i + 1])
    return (xs, ys)
    if reverse is True:
            x = xs.reverse()
            y = ys.reverse()
    return(x, y)

for some reason when reverse is True the lists are not being reversed, they are the same as when reverse is False

Bhargav Rao
  • 50,140
  • 28
  • 121
  • 140
tribo32
  • 333
  • 3
  • 15

3 Answers3

2

The reason reverse = True is not working is that you have a return statement right before the check:

return (xs, ys)

The code after the return statement is never executed.

Additionally, reverse() reverses the list in place and returns None, so x and y will end up being None.

Here is how both issues can be fixed:

if reverse:
        xs.reverse()
        ys.reverse()
return (xs, ys)

Finally, you could use slicing instead of an explicit loop to extract the odd/even elements:

In [7]: x = [1, 2, 3, 4, 5, 6, 7, 8]

In [8]: x[::2]
Out[8]: [1, 3, 5, 7]

In [9]: x[1::2]
Out[9]: [2, 4, 6, 8]
NPE
  • 486,780
  • 108
  • 951
  • 1,012
0

reverse() does not return any value. It reverses the list in place. So the reversed list is in xs and in ys.

http://www.tutorialspoint.com/python/list_reverse.htm

Also you are returning before you execute the if statement.

0
return (xs, ys)
if reverse is True:

In functions, after return everything is not working. That's why your if statement is not working. It's making everything ineffective after return. You can imagine it like;

def wr():
    x="hey"
    y="Hello"
    return x
    return y
print (wr())

Like this one, this function going to write only hey, because it returned one time and other return y is ineffective anymore.

GLHF
  • 3,835
  • 10
  • 38
  • 83