IndexError: list assignment index out of range - Printable Version +- Python Forum (https://python-forum.io) +-- Forum: Python Coding (https://python-forum.io/forum-7.html) +--- Forum: General Coding Help (https://python-forum.io/forum-8.html) +--- Thread: IndexError: list assignment index out of range (/thread-7288.html) |
IndexError: list assignment index out of range - ted_chou12 - Jan-03-2018 I am trying to create a multiple dimension array with predefined index: returns = [] for s in context.securities: returns[s] = [] print(returns)but the above code returns Quote:IndexError: list assignment index out of range Thank you! Ted RE: IndexError: list assignment index out of range - Larz60+ - Jan-03-2018 you don't explain what context.securities looks like This what I think you want returns = [] for s in context.securities: returns.append([]) print(returns) RE: IndexError: list assignment index out of range - buran - Jan-03-2018 Larz is right that you don't explain what context.securities looks like and what the solution is. I just want to explain the cause of the error. List is mutable object and returns[s] = [] is the syntax for changing element at index s . However returns is empty list so, whatever the value of s is, there is no element at index s (i.e. index value s is out of the range of available indexes, which is in fact empty range)>>> returns = [] >>> returns[0] = 10 Traceback (most recent call last): File "<stdin>", line 1, in <module> IndexError: list assignment index out of range >>> returns.append(10) >>> returns [10] >>> returns[0] = 1 >>> returns [1] >>> RE: IndexError: list assignment index out of range - ted_chou12 - Jan-03-2018 Sorry for the lack of information: context.securities looks like this: PRINT [Equity(24 [AAPL]), Equity(16841 [AMZN])] returns = [] for s in context.securities: returns.append([]) print(returns)Seems to be fine for creating the array for each element in the context.securities, but I wonder how can I create the index of s in the returns list so that I can call print(returns[s]) when I iterate through each?Thank you so much! RE: IndexError: list assignment index out of range - buran - Jan-03-2018 well, PRINT [Equity(24 [AAPL]), Equity(16841 [AMZN])]is (i) not a valid python code and (ii) - not something you can iterate over I take my words back - [Equity(24 [AAPL]), Equity(16841 [AMZN])] looks like a list of custom class objects. However it is not clear how you derive returns for each security, e.g. Equity(24 [AAPL]) what external package do you use to produce context.securities |