2

Let's say I have the following for loop:

d = defaultdict(int)
for f in foo:
    for b in f:
        d[b] += 1

I ripped my actual example of bloat which is unrelated to my question. Now I want to somehow shorten it. In e.g. list comprehensions we are allowed to use nested for loops, and if they're done properly they can be perfectly readable. So we reduce nesting and the amount of lines. My question here is, can we do nested for loops without doing the comprehension, so we would end with something like this, in Python?:

d[b] += 1 for b in for f in foo

0

1 Answer 1

3

You could use itertools.chain:

for b in itertools.chain.from_iterable(foo): d[b] += 1

Notice that when trying to do this d[b] += 1 for b in for f in foo (which is of course invalid sintax) your intention is to mutate something, and that should not be done inside a comprehension.

Sign up to request clarification or add additional context in comments.

4 Comments

+1. Additionally, collections.Counter(itertools.chain.from_iterable(foo)) should simplify it even further
What if I need to pass f to some other function, in my case: for b in windowed(f, 2)?
@dabljues, I would stick to the nested for loop in that case. I think it would be the most readable thing to do.
Sorry for my absence. Yeah, I guess you're right. Marking your answer as accepted, thank you!

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.