0

I have written a function that reverses the values of a string:

def reversed_list(in_list):
    """A function that reverses the order 
    of the items in a list"""
    
    flipped_list = []
    
    [flipped_list.insert(0, in_list[k]) for k, v in enumerate(in_list)]
        
    return flipped_list
    
reversed_list([1, 2, 3, 4, 5, 6])

It works as expected. However, if I combine the last two lines of the function to become:

return [flipped_list.insert(0, in_list[k]) for k, v in enumerate(in_list)]

The outputted list is [None, None, None...]

Why is this and how can I combine these last two lines to make this code as elegant as possible?

Cheers,

GalacticPonderer
  • 497
  • 3
  • 16
  • 2
    Why are you using a list comprehension here? A simple for loop would be the correct choice – UnholySheep Sep 10 '20 at 17:36
  • 2
    You don't need `enumerate`, either. The only reason you need `k` is to compute `in_list[k]`, but `v` is already `in_list[k]`. `flipped_list.insert(0, v) for v in in_list` would suffice. – chepner Sep 10 '20 at 17:42
  • And there's little reason trying to find something more elegant than `return list(reversed(in_list))`. – chepner Sep 10 '20 at 17:43
  • @chepner: Or just `return in_list[::-1]` if the input is expected to be a `list`, or returning the same type as the input is fine. – ShadowRanger Sep 10 '20 at 17:49
  • @chepner, I am just playing around and would normally use `reverse()`. Basically, I am going through Python functions and trying to rewrite them as elegantly as possible from scratch. TBH, I don't want to be using `.insert()` either. Thanks for the trimming in your first response though – GalacticPonderer Sep 10 '20 at 17:53
  • @UnholySheep - Correct me if I am wrong, but are list comprehensions just elegant one-line loops? – GalacticPonderer Sep 10 '20 at 17:54
  • Does this answer your question? [Python's insert returning None?](https://stackoverflow.com/questions/1516889/pythons-insert-returning-none) – Georgy Sep 10 '20 at 17:56
  • 1
    *"are list comprehensions just elegant one-line loops"* - No, list comprehensions are dedicated syntax to create lists filled with calculated elements (and optimized in the interpreter itself). Using it when you have no intention of using the created list is just a waste (allocating a list object that is immediately discarded) – UnholySheep Sep 10 '20 at 18:03
  • Fair point. However, I am returning the list, then using it outside the function. So, is your point applicable in this situation? – GalacticPonderer Sep 10 '20 at 18:36

1 Answers1

3

flipped_list.insert modifies the list in place, and returns None.

If the first example, you are updating flipped_list within the list comprehension and then are returning the modified list.

In the second example, you are still modifying flipped_list, but returning the list that was created in the list comprehension which is filled with None values

Wondercricket
  • 7,651
  • 2
  • 39
  • 58