Ad

Two Opposing Iterators, List Assignment Index Range Error

- 1 answer

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 = 0
j = number - 1
while i < number or j >= 0:
    list_copy[i] = my_list[j]
    i += 1
    j -= 1

for 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?

Ad

Answer

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 - 1
while j >= 0:
    list_copy.append(my_list[j])
    del my_list[j] # if you need remove elements from original list
    j -= 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.

Ad
source: stackoverflow.com
Ad