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

后端 未结 5 891
长发绾君心
长发绾君心 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:40

    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
    

提交回复
热议问题