user2572329
user2572329

Reputation: 35

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

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

Also have an index number, this number will tell where to start the reversing. For example, if the reverse-index number is 3, it needs to be something like this: ['d', 'c', 'b', 'a', 'e', 'f']

What I currently have:

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

    n_list = []

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

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

Which returns ['c', 'b', 'a', 'f', 'e', 'd']

How can I alter my code, so that it prints out ['d', 'c', 'b', 'a', 'e', 'f']?

Upvotes: 2

Views: 616

Answers (5)

RoadRunner
RoadRunner

Reputation: 26335

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

Upvotes: 0

hilberts_drinking_problem
hilberts_drinking_problem

Reputation: 11602

You can modify the list inplace using a slice.

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

Upvotes: 0

Luis
Luis

Reputation: 3497

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

Upvotes: 0

Dunes
Dunes

Reputation: 40903

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

Upvotes: 2

Selcuk
Selcuk

Reputation: 59444

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))

Upvotes: 2

Related Questions