How can I reverse a section of a list using a loop in Python?

只愿长相守 提交于 2019-12-02 01:38:55

Is it allowed to make a copy of the list?

def list_section_reverse(list1, reverse_index):
    print("In function reverse()")

    n_list = [ element for element in list1 ]

    for item in range( reverse_index + 1 ):
        n_list[ item ] = list1[ reverse_index - item ]
        item += 1

    return n_list

mylist = ['a', 'b', 'c', 'd', 'e', 'f']
print(list_section_reverse(mylist, 3))

Outs:

In function reverse()
['d', 'c', 'b', 'a', 'e', 'f']

You can simply use:

def list_section_reverse(list1, reverse_index):
    return list(reversed(list1[:reverse_index+1])) + list1[reverse_index+1:]

Edit: The problem with your existing solution is that you keep reversing after reverse_index. If you have to use a loop, try this:

def list_section_reverse(list1, reverse_index):
    print("In function reverse()")

    n_list = list1[:]

    for i in range(reverse_index + 1):
        n_list[i] = list1[-i-reverse_index]
    return n_list

mylist = ['a', 'b', 'c', 'd', 'e', 'f']
print(list_section_reverse(mylist, 3))

The pythonic solution:

list1[reverse_index::-1] + list1[reverse_index+1:]

Now, that's not using loops like you asked. Well, not explicitly... Instead we can break down the above into its constituent for loops.

def list_section_reverse(list1, reverse_index):
    if reverse_index < 0 or reversed_index >= len(list1):
        raise ValueError("reverse index out of range")
    reversed_part = []
    for i in range(reverse_index, -1, -1): # like for i in [n, n-1, ..., 1, 0]
        reversed_part.append(list1[i]

    normal_part = []
    for i in range(reverse_index + 1, len(list1)):
        normal_part.append(list1[i])

    return reversed_part + normal_part

You can modify the list inplace using a slice.

mylist[:4] = mylist[:4][::-1]

You can try this. This makes use of no slicing, and can use either a while loop or for loop.

    def reversed_list(my_list, index):
        result = []
        list_copy = my_list.copy()

        i = 0
        while i < index+1:
            result.append(my_list[i])
            list_copy.remove(my_list[i])
            i+=1

        result.reverse()

        return result + list_copy

Or with a for loop

    def reversed_list(my_list, index):
        result = []
        list_copy = my_list.copy()

        for i in range(len(my_list)):
            if i < index + 1:
                result.append(my_list[i])
                list_copy.remove(my_list[i])

        result.reverse()

        return result + list_copy
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!