1

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.

1
  • You overcomplicated things and then everything went wrong. Why not a simple if len(j) == 4:? Commented Jun 16, 2022 at 14:11

3 Answers 3

4

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

1 Comment

Thank you! Let me please accept nonDucor's answer instead of yours simply because it is more general.
2

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]

Comments

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

1 Comment

Your answer could be improved with additional supporting information. Please edit to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers in the help center.

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.