What will be python single line equivalent of below code?
l=[]
for i in range(3,5) :
if i==3:
for j in range(0,2):
if i%2:
l.append(i*j)
else:
l.append(i+j)
else:
l.append(i)
print(l)
I tried using a single line for nested loop but with only one condition like this:
print([i*j if i%2 else i+j for i in range(3,5) for j in range(0,2)])
Note: Here i want to learn how to use single line equivalent for nested loops with if else condition in both the loops. Also if it's not possible then specify why not!
Thanks in advance :)
You can transform your inner portion into a sequence of lists:
[[i * j if i % 2 else i + j for j in range(2)] if i == 3 else [i] for i in range(3,5)]
Unrolling a 2D iterable is easy in the general case:
[e for row in iterable for e in row]
Combining the two:
[e for row in [[i * j if i % 2 else i + j for j in range(2)] if i == 3 else [i] for i in range(3,5)] for e in row]
You can avoid storing intermediate lists by using generators:
[e for row in ((i * j if i % 2 else i + j for j in range(2)) if i == 3 else [i] for i in range(3,5)) for e in row]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With