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

后端 未结 5 935
长发绾君心
长发绾君心 2021-01-23 05:45

I\'m in need of a little help reversing a section of a list in Python using a loop.

I have a list: mylist = [\'a\', \'b\', \'c\', \'d\', \'e\', \'

5条回答
  •  天命终不由人
    2021-01-23 06:42

    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
    

提交回复
热议问题