Melon987
Melon987

Reputation: 49

How do I print out this list of lists?

count: int = 0
while count < len(stocksOwned):
    print(stocksOwned[count][count][0],'\nsakuma cena-',stocksOwned[count][count][1])
    count += 1

stocksOwned = [[['Microsoft', 150, 0.01, 0, 0]], [['Tesla', 710, 0.0424, 0, 0]]]

Traceback: print(stocksOwned[0][count][0],'\nsakuma cena-',stocksOwned[0][count][1]) IndexError: list index out of range

I can't seem to figure why the index is out of range. I know indexing starts with 0. What am I not seeing or understanding here?

Upvotes: 1

Views: 60

Answers (3)

mkapuza
mkapuza

Reputation: 21

This is actually a list of lists of lists... Here's how you print:

for stock in stocksOwned:
     print(stock[0][0],'\nsakuma cena-',stock[0][1])

You may mean to have:
stocksOwned = [['Microsoft', 150, 0.01, 0, 0], ['Tesla', 710, 0.0424, 0, 0]] (a list of lists)

Upvotes: 1

Anurag Reddy
Anurag Reddy

Reputation: 1215

Your second dimension of list has only 1 index.

stocksOwned[count][0][0]

will give you the correct value. Having stocksOwned[count][count][0] will make it index the next list which is not there.

stocksOwned[0]
[['Microsoft', 150, 0.01, 0, 0]]
stocksOwned[0][0]
['Microsoft', 150, 0.01, 0, 0]
stocksOwned[0][0][0]
'Microsoft'

This is how it looks. so indexing 1 in the middle one will throw error.

Upvotes: 0

Code Pope
Code Pope

Reputation: 5449

You are calling stocksOwned[count][count] and this results to the error based on stocksOwned = [[['Microsoft', 150, 0.01, 0, 0]], [['Tesla', 710, 0.0424, 0, 0]]]. Use the following code:

while count < len(stocksOwned):
    print(stocksOwned[count][0][0],'\nsakuma cena-',stocksOwned[count][0][1])
    count += 1

Upvotes: 1

Related Questions