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

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

    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']
    

提交回复
热议问题