This code is supposed to reverse the first number items in my_list, while keeping the remainder of the list in its original order.

list_copy=[]i=0j=number - 1while i < number or j >=0:list_copy[i]=my_list[j]i +=1j -=1for i in range(number,length(my_list)):list_copy[i]=my_list[i]

I've used pen & paper to run the iterations and can't figure out why I'm getting "list assignment index out of range". What am I missing?

    list_copy=my_list[0:NUMBER-1]

    - copy first NUMBER elements from my_list to list_copy

    my_list=my_list[NUMBER-1:]

    - remove first NUMBER elements from my_list

    Update, without slicing:

    list_copy=[]j=number - 1while j >=0:list_copy.append(my_list[j])del my_list[j] # if you need remove elements from original listj -=1

    You did have "index out of range" because Python interpreter tries to get list_copy[i] from the empty list. Just use list_copy.append() for filling empty lists.

    • I need to achieve it without using slicing. It's a homework assignment.– SoundscapeNov 18 at 10:40
    • Updated, without slicing– moveax3Nov 18 at 10:51
    • Brilliant, thanks.– SoundscapeNov 20 at 7:38

    Your Answer

    By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

    Not the answer you're looking for? Browse other questions tagged or ask your own question.