Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create a single-line script with two for loops, in the debugger, in python 2.7

Creating a single line for loop in the python debugger or django shell is easy:

>>>> for x in (1,2,3,4):print(x);
>>>> for x in Obj.objects.all():something(x);

But how can I get a second for loop in there?

>>>> for x in (1,2,3,4):print x;for y in (5,6):print x,y;
SyntaxError: invalid syntax

I care because it's nice to have up arrow edit of the prior command, when working interactively (this is not an attempt to use single line commands in any other context).

NOTE: the "print" is just an example. In real use I'd iterate objects or perform other programming or debugging tasks such as 'for s in Section.objects.all():for j in s.children():print j'. I am using Python 2.7.

like image 739
Bryce Avatar asked Jan 20 '26 00:01

Bryce


2 Answers

For the times that a list comprehension just won't do

for x in (1,2,3,4):print x;exec("for y in (5,6):print x,y;")

or

for s in Section.objects.all():exec("for j in s.children():print j")

Sometimes you can use itertools.product (But there's no way to get the print x) like this

for x, y in itertools.product((1,2,3,4), (5,6)):print x,y)
like image 110
John La Rooy Avatar answered Jan 22 '26 14:01

John La Rooy


List comprehension may be used to achieve what you want. What you want exactly is NOT possible.

>>> [(x, y) for x in (1, 2, 3, 4) for y in (5, 6)]
[(1, 5), (1, 6), (2, 5), (2, 6), (3, 5), (3, 6), (4, 5), (4, 6)]

Related: Single Line Nested For Loops

like image 38
KGo Avatar answered Jan 22 '26 14:01

KGo



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!