Getting errors when computing the length of list of lists

Viewed 36

I have a list of lists. I am trying to find the indices of lists whose length is 4. Here is the code:

for i, j in enumerate(list_of_lists):
  if [x for x in list_of_lists if len(x) == 4] in j:
    print(i)

Alongside the correct indices, I also get the index of a list whose length is 1. Is there something wrong in my code? I have no idea why this happens.

3 Answers

When you iterate over list_of_lists like so, j is the inner list, so you need to check whether len(j) == 4:

list_of_lists = [[0, 1, 2, 3], [], [0], [0, 1, 2, 3],]

for i, j in enumerate(list_of_lists):
    if len(j) == 4:
        print(i)
# 0
# 3

If you prefer to collect the indices instead of printing them, it is even simpler:

indices = [i for i, j in enumerate(list_of_lists) if len(j) == 4]
    for i, j in enumerate(list_of_lists):
        if len(j) == 4:
            print(i)

Can you try this code? Actually, i is the index, and j is the value.

Related