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.
2 Answers 2
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)
1 Comment
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])
Comments
Explore related questions
See similar questions with these tags.
print(PrintedList)
, so we can take a look at the actual structure. We can't guess by looking at code that doesn't work =)PrintledList[index][1]
andPrintedList[index][2]
?