0

In python I'm trying to write nested loops in one line. I've seen a lot of examples, but in all of them the inner iterable variable is different compared to the outer one. So in my case, it won't work. Here's my try:

my_list = [for ip in subnet for subnet in subnets]

where I'm getting:

Unresolved reference 'subnet' 
3
  • checkout stackoverflow.com/questions/24591917/nested-loop-python Commented Nov 10, 2022 at 16:53
  • 1
    @YUVI_1303 it seems you didn't read my question :) Commented Nov 10, 2022 at 16:58
  • [ip for subnet in subnets for ip in subnet] Commented Nov 10, 2022 at 16:59

2 Answers 2

1

There is a syntax error, it should be

my_list = [ip for subnet in subnets for ip in subnet]
Sign up to request clarification or add additional context in comments.

3 Comments

didn't work in this case: [pool.apply_async(handle_ip, (ip,)) for ip in subnet for subnet in subnets]
It's unintuitive, but you have to flip the loop conditions to ensure that the loop variables are declared in the proper order. [pool.apply_async(handle_ip, (ip,)) for subnet in subnets for ip in subnet]
You're 100% right, edited answer above.
-1

Try with this

my_list = [[ip for ip in subnet] for subnet in subnets]

is a way to nest loops in list comprehension

Can check this too https://www.geeksforgeeks.org/nested-list-comprehensions-in-python/

3 Comments

That inner comprehension should be [ip for ip in subnet]. It doesn't make sense to start a list comprehension with for.
this doesn't even compile
@0x5453 sorry my mistake, i forgot to put ip at the start. I'm going to edit it.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.