Reputation: 1
In the tutorial video I was watching the range used in for loop was "range(len(l))" which successfully reversed the list.
But I guess simply putting " l " will solve the purpose and it didn't can someone please tell me why is that?
def reversed_list(l):
rev = []
for i in l:
l_popped = l.pop()
rev.append(l_popped)
return rev
SAMPLE_LIST = [1,2,3,4]
print(reversed_list(SAMPLE_LIST))
OUTPUT:
[4, 3]
Upvotes: 0
Views: 1608
Reputation: 5281
I'm not sure what the tutorial you watched did, but range(len(_))
will not reverse, it just creates a range
of the size of your list, starting at 0.
If you want to reverse a list in Python, just use the builtin reversed
:
l = list("hello")
print(list(reversed(l))) # at list to have an actual list as opposed to an iterator
# ['o', 'l', 'l', 'e', 'h']
print(range(len(l)))
# range(0, 5)
PS: The reason your solution doesn't work is you're changing the object you iterate over during the iteration by using pop
. A simple way to debug this is to add a print statement:
def reversed_list(l):
rev = []
for i in l:
print("This is l:", l)
l_popped = l.pop()
rev.append(l_popped)
return rev
print(reversed_list([1,2,3,4]))
# This is l: [1, 2, 3, 4]
# This is l: [1, 2, 3]
# [4, 3]
Upvotes: 1
Reputation:
If you really want to use pop
to reverse a list, you can make a shallow copy of the original list. Every time you iterate, the length of the list reduces
>>> x=[1,2,3,4]
>>> z=x.copy()
>>> y=[x.pop(i) for i in range(len(z)-1,-1,-1)]
>>> y
[4, 3, 2, 1]
Upvotes: 0
Reputation: 146
This loop is root cause of problem.
for i in l:
l_popped = l.pop()
rev.append(l_popped)
return rev
Let us try to dry run.
When i = 1 (index 0), it pops 4 and rev = [4], l = [1, 2, 3]
When i = 2 (index 1), it pops 3 and rev = [4, 3], l = [1, 2]
Now, index crosses the length of l hence operation on remaining elements are not executed.
Upvotes: 0