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' 
cmauck10
  • 163
  • 3
Algo
  • 11
  • 4

2 Answers2

1

There is a syntax error, it should be

my_list = [ip for subnet in subnets for ip in subnet]
cmauck10
  • 163
  • 3
  • didn't work in this case: `[pool.apply_async(handle_ip, (ip,)) for ip in subnet for subnet in subnets]` – Algo Nov 10 '22 at 17:03
  • 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]` – 0x5453 Nov 10 '22 at 17:05
  • You're 100% right, edited answer above. – cmauck10 Nov 10 '22 at 17:07
-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/

Ljg
  • 141
  • 8