2

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

5 Answers 5

2

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))
Sign up to request clarification or add additional context in comments.

6 Comments

I want to achieve this using a loop, not with built-in functions.
@Selcuk Sorry, I thought mentioning that I only have to use loops in my title would have been enough. Turns out not.
@Selcuk Now, I get an error stating IndexError: list assignment index out of range
@user2572329 It works fine for me, are you sure you are running the same code? Note that initialization of n_list has also changed.
@Selcuk Yep, same code, but different list (same size list). I can't see anything different...
|
2

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

Comments

0

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

2 Comments

This works, and works with all sizes of Lists. Appreciate it mate, thanks.
Glad it helped! ^_^
0

You can modify the list inplace using a slice.

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

Comments

0

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

4 Comments

oops sorry, I didnt see the loop part in the description. I will add that
Cheers. Also, if possible, can I accomplish this without slice expressions?
I updated the answer. Do you still want to remove all sorts of slicing?
@user2572329, this solution has no slicing, and uses only one loop each.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.