Home > Software design >  How do I iterate through lists with nested lists in Python / why doesn't my code work?
How do I iterate through lists with nested lists in Python / why doesn't my code work?

Time:08-07

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.)

CodePudding user response:

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])

CodePudding user response:

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)):

CodePudding user response:

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.

  • Related