I have a class that I built and when I print the list in which the len is 150. This is a list of lists like the following:
[{'id': '1344125', 'date': '2022-01-16', 'money': '158.0', 'vat': '7.6', 'payment': 'PayPal'}], [{'id': '1234125', 'date': '2022-01-12', 'money': '124.0', 'vat': '12.12', 'payment': 'CC'}]]
When I am trying to get into a value in one of the lists I get an error
print(lst[0][1])
IndexError: list index out of range
Why does it happen?
CodePudding user response:
data = [[{'id': '1344125', 'date': '2022-01-16', 'money': '158.0', 'vat': '7.6', 'payment': 'PayPal'}], [{'id': '1234125', 'date': '2022-01-12', 'money': '124.0', 'vat': '12.12', 'payment': 'CC'}]]
# type list
print(type(data))
# data
print(data[0][0])
# access element 'id' in data
print(data[0][0]['id'])
Output:
<class 'list'>
{'id': '1344125', 'date': '2022-01-16', 'money': '158.0', 'vat': '7.6', 'payment': 'PayPal'}
1344125
CodePudding user response:
This is how your list looks like:
[ # outer list [ # inner list 1 {} # single element inside inner list 1 ], [ # inner list 2 {} # single element insider inner list 2 ], ... ]
Since all inner lists consists of a single item, that item can only be accessed using 0th index. Using any other index would be illegal and throw index out of range exception.
Here's how this could be debugged:
print(len(outer_list)) for inner_list in outer_list: print(len(inner_list))
CodePudding user response:
Because yout list is out of range. You are accessing second place value which does not exist as len(lst) is 1
and you can to access this with lst[0]
.
try using
print(lst[0][0]['id'])
.
First namespace[0]
gives you -
[{'id': '1344125', 'date': '2022-01-16', 'money': '158.0', 'vat': '7.6', 'payment': 'PayPal'}]
Second namespace [0]
gives you
{'id': '1344125', 'date': '2022-01-16', 'money': '158.0', 'vat': '7.6', 'payment': 'PayPal'}
and last namespace ['id']
- 1344125