0

I have the following structure

list1 = ["ab","ac","cd","de","fh","abcc","abcdef"]
list2 = ["acebfh"]
comprehension = [item for item in list1
                 if list(list2).count(i) < list(item).count(i) 
                 for i in set(list2)]

but returns:

i is referenced before assignment

Is there a way to do this with list comprehension ?

4
  • 5
    What is your expected output? May 7, 2017 at 4:03
  • 3
    For good style, list comprehensions are best used for simple loops. Use a regular for loop for more complex loops and tests.
    – Keith
    May 7, 2017 at 4:08
  • 2
    The answer to your questions is "yes" and there are a few more thorough answers below, but the confusion you're experiencing here is a good example of why complicated list comprehensions are best avoided.
    – Shep
    May 7, 2017 at 4:22
  • The test is meaningless, as it will always be False. set(list2) is just set with one item in it, so i = "acebfh". list(list2) just recreates list2 which has i in it, so list(list2).count(i) == 1 but list(item).count(i) will be 0 for every item. What do you expect list(list2) and list(list1) to do?
    – AChampion
    May 7, 2017 at 4:32

2 Answers 2

2

List comprehensions are written in the same order as their nested full-specified counterparts, so lets unpack this. What you wrote essentially translates to:

for item in list1:
    if list(list2).count(i) < list(item).count(i):
        for i in set(list2):
            list.append(item)

Notice that we are referencing i in the if statement before it's defined in the for loop.

If what you want is the equivalent of this:

for item in list1:
    for i in set(list2):
        if list(list2).count(i) < list(item).count(i):
            list.append(item)

then you could write your list comprehension as:

comprehension = [item for item in list1
                 for i in set(list2)
                 if list(list2).count(i) < list(item).count(i)]
0
0

List comprehension for nested loops is the opposite of what you might expect. You're trying to do something like

[i for i in range(j) for j in range(10)]

whereas you should be doing something like

[i for j in range(10) for i in range(j)]

In other words, the "inner" loop comes after the outer one, whereas you have the the inner loop (and condition) coming first.

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.