2

I'm trying to define a new function called new_f, just for practice:
The purpose of function is:

x = ['1', '2', '3', '4'] y = new_f(x) print(y) 

And that should give:

['4', '3', '2', '1'] 

So it's a reverse of x.
I tried something like this:

def new_f(x): y = len(x) for z in range(y-1,-1,-1): r = print([x[z]]) return r 

But that gives:

['4'] ['3'] ['2'] ['1'] 

Ok, that's not what I want, so maybe:

--------- for z in range(y-1,-1,-1): r = [x[z]] return r 

And I get:

['1'] 

So he goes through all z and gives me the last one.
How can I resolve this problem?
Thanks in advance.

3
  • 1
    list reverse is list[::-1] Commented Apr 29, 2015 at 23:01
  • What's the for z in range(y-1,-1,-1) loop iterating on? Commented Apr 29, 2015 at 23:01
  • list[::-1] means you've masked the built-in function list() with a reference to an object of type list. Commented Apr 29, 2015 at 23:04

3 Answers 3

4

You can initial r as an empty list and append the elements to it and at last return the r

def new_f(x): y = len(x) r=[] for z in range(y-1,-1,-1): r.append(x[z]) return r 

But there are some elegant and more pythonic ways for reversing a list like reverse indexing :

the_list[::-1] 

or built-in reversed function :

reversed(the_list) 
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you @Kasra that's exactly how I wanted.
3

You can use Python's slicing operator to reverse a list.

def new_f(x): return x[::-1] 

Comments

1

Maybe you'd find them useful:

def reverse_list(x): return x.reverse() def reverse_list(x): return x[::-1] def reverse_list(x): yield from reversed[x] 

2 Comments

Hey, I think instead of yield from reversed(x) you can just do return reversed(x). I mean it's the same exact thing, just shorter, and faster.
oh, yes. It's returns list_reverseiterator empty instance but yield returns a generator empty instance, that's the only difference :D

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.