Question

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.

Was it helpful?

Solution

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)

OTHER TIPS

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

You could end up putting the command first. For Example.

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

You do end up with one problem however. Unless you want to call a function at the beginning I do not believe there is a way. For example.

>>> [doSomething(x, y) for x in (1, 2, 3, 4) for y in (5, 6)]
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top