简体   繁体   中英

Reversing a list with pop & insert

Any ideas why reverse_1 reverses input list but reverse_2 doesn't?

I have run both in the debugger and the issue seems to be that reverse_2 doesn't return the reversed list.

def reverse_1(seq):
    return_list = list()
    for i in range(len(seq)):
        return_list.append(seq.pop())
    seq.extend(return_list)


def reverse_2(seq):
    length = len(seq)
    for i in range(length):
        seq.insert(0, seq.pop())


example = [1, 2, 3, 4, 5, 6]
reverse_1(example) #OUTPUT - [6, 5, 4, 3, 2, 1]
reverse_2(example) #OUTPUT - [1, 2, 3, 4, 5, 6]

.insert(0, n) will insert n in front of the list, so in the first iteration it pops 6 and inserts it at the beginning:

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

The second iteration will pop 5 and similarly insert it:

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

A possible solution would be to change the line to:

seq.insert(i, seq.pop())

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM