0

Can someone explain why Python won't let me use i in this manner?

unit1 = [["cats allowed", True], ["bedrooms", 0], ["Balcony", False]]

userPref = []
for i in unit1:
   userPref = userPref.append(unit1[i][1])
   print(unit1[i][1])

I get this error message:

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

If I want to iterate through the second item in each nested list, how would I go about doing that?

(FYI: the for loop in nested in an if statement. I omitted that for simplicity.)

3
  • did you debug it ? print(i) in the loop you'll understand, you iterate over values, not indices Commented Aug 6, 2022 at 16:56
  • 2
    Does this answer your question? TypeError: list indices must be integers or slices, not list Commented Aug 6, 2022 at 17:01
  • you didn't use append correctly, you can see the correct format in my answer Commented Aug 6, 2022 at 17:32

3 Answers 3

2

Some options you have to iterate over a list:

1)

for item in unit1:
   userPref.append(item[1])
   print(item[1])

which item[1] is the second parameter of nested list

2)

for i in range(len(unit1)):
    userPref.append(unit1[i][1])
    print(unit1[i][1])

or if you need item and index together:

for i,item in enumerate(unit1):
    userPref.append(item[1])
    print(item[1])
Sign up to request clarification or add additional context in comments.

Comments

1
for i in unit1:

When you iterate over a list in this way, i becomes each value in the list, not the list index.

So on the first iteration, i is the sub-list ["cats allowed", True].

If you want to iterate over the indexes of a list, use range():

for i in range(len(unit1)):

Comments

0

Python’s for statement iterates over the items of any sequence (a list or a string), in the order that they appear in the sequence.

You can found that differ in python official tutorial, the iteration will traverse all the value in the sequence rather index of that, which is quite different from other languages.

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.