Two Opposing Iterators, List Assignment Index Range Error
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?
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.
- → What are the pluses/minuses of different ways to configure GPIOs on the Beaglebone Black?
- → Django, code inside <script> tag doesn't work in a template
- → React - Django webpack config with dynamic 'output'
- → GAE Python app - Does URL matter for SEO?
- → Put a Rendered Django Template in Json along with some other items
- → session disappears when request is sent from fetch
- → Python Shopify API output formatted datetime string in django template
- → Shopify app: adding a new shipping address via webhook
- → Shopify + Python library: how to create new shipping address
- → shopify python api: how do add new assets to published theme?
- → Access 'HTTP_X_SHOPIFY_SHOP_API_CALL_LIMIT' with Python Shopify Module