PuzzledByPython
PuzzledByPython

Reputation: 13

How to use a for loop to loop through a nested list in Python

I am currently trying to loop through and print specific values from a list. The way that I am trying to do this is like this.

for i in range(len(PrintedList)):
     index = i
     elem=PrintedList[i]
     print(elem)
     print ("Product = ", PrintedList [index,1], "price £",PrintedList [index,2])

However this returns the error of :

TypeError: list indices must be integers or slices, not tuple.

I am really unsure of what to do to fix the problem.

Upvotes: 0

Views: 2836

Answers (2)

myaut
myaut

Reputation: 11504

Please do not iteerate using indeces, this is ugly and considered non-pythonic. Instead directly loop over list itself and use tuple-assignment, i.e.:

for product, price, *rest in PrintedList:
     print ("Product = ", product, "price £", price)

or

for elem in PrintedList:
     product, price, *rest = elem
     print ("Product = ", product, "price £", price)

*rest only required if some sublists contain more than 2 items (price and product)

if you need indeces, use enumerate:

for index, (product, price, *rest) in enumerate(PrintedList):
     print (index, "Product = ", product, "price £", price)

Upvotes: 4

SgtStens
SgtStens

Reputation: 300

When you're referencing a nested list, you reference each of the indices in separate brackets. Try this:

for i in range(len(PrintedList)):
    index = i
    elem=PrintedList[i]
    print(elem)
    print ("Product = ", PrintedList [index][1], "price £",PrintedList [index][2])

Upvotes: 0

Related Questions