1

I am trying to make a reversed sequence in python and wrote this code:

def reverse_seq(n):

    sorted([i for i in range(1, n+1)], reverse=True)
print(reverse_seq(6))

but it gives me None.

10 Rep
  • 2,217
  • 7
  • 19
  • 33
Ana Rad
  • 43
  • 6
  • 4
    The `reverse_seq` function doesn't include a `return` – JeffUK Dec 08 '20 at 16:54
  • 2
    1. You can use the builtin function `reversed`. 2. In this case there's no need to use `reversed`, just use `range(n+1, 1, -1)` – Roy Cohen Dec 08 '20 at 16:55
  • Is there a reason you can't use `list(reversed(n))`? Is this a learning exercise, or homework or something? – Random Davis Dec 08 '20 at 16:56
  • Does this answer your question? [Python Script returns unintended "None" after execution of a function](https://stackoverflow.com/questions/16974901/python-script-returns-unintended-none-after-execution-of-a-function) – Tomerikoo Dec 08 '20 at 17:02

3 Answers3

2

In some programming languages, the last expression in a function is implicitly the value it returns. But in python, you have to have a return statement, or you get None.

def reverse_seq(n):
    return sorted([i for i in range(1, n+1)], reverse=True)
kojiro
  • 74,557
  • 19
  • 143
  • 201
2

You can use the range function like so:

def reverse_seq(n):
    return range(n + 1, 1, -1)
  • use list(range(n + 1, 1, -1)) if the output must be a list.
Roy Cohen
  • 1,540
  • 1
  • 5
  • 22
  • I like this answer, no need to sort a range you just made; you get that for free – ccluff Dec 08 '20 at 17:53
  • also, I just timed this way compared to the sorted() method, and at low list sizes (about 10 items) this way is roughly 2x faster, but at list sizes of 1000 the this is more like 1000x faster. Note: this is with the list(range(n + 1, 1, -1)), if you leave the list() off it gets even faster – ccluff Dec 08 '20 at 17:59
1
def reverse_seq(n):
    return  sorted([i for i in range(1, n+1)], reverse=True)
print(reverse_seq(6))

OUTPUT

>> [6, 5, 4, 3, 2, 1]

Note: You have to use return to return the value from a function otherwise it'll return None as output.

Yash Makan
  • 706
  • 1
  • 5
  • 17