-1

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
  • Post the output (or a small sample) of print(PrintedList), so we can take a look at the actual structure. We can't guess by looking at code that doesn't work =) Commented Feb 16, 2017 at 15:20
  • Is it possible you meant PrintledList[index][1] and PrintedList[index][2]? Commented Feb 16, 2017 at 15:21

2 Answers 2

4

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)
Sign up to request clarification or add additional context in comments.

1 Comment

Definitely the more pythonic way to do it, I was merely trying to address the specific error in the code. + 1 for the *rest, I didn't know about that.
0

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.