0

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]
Andrej Kesely
  • 168,389
  • 15
  • 48
  • 91
  • 1
    Because you're altering the list (with `l.pop()`) while looping over the list. So your list get shortened while you loop over the list. – 9769953 Jul 11 '21 at 12:41
  • do not change the list you are iterating over. for reversing you can use `return list(reverse(l))` function or slicing `return l[::-1]` – Patrick Artner Jul 11 '21 at 12:50

3 Answers3

1

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]

niko
  • 5,253
  • 1
  • 12
  • 32
0

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.

ankush__
  • 141
  • 9
0

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]