2

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.

Bryce
  • 8,313
  • 6
  • 55
  • 73

3 Answers3

6

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)
John La Rooy
  • 295,403
  • 53
  • 369
  • 502
3

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

Community
  • 1
  • 1
KGo
  • 18,536
  • 11
  • 31
  • 47
0

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)]
KodyVanRy
  • 1,110
  • 1
  • 14
  • 25
  • >>> [print("hi") for x in (1, 2, 3, 4) for y in (5, 6)] SyntaxError: invalid syntax – Bryce Oct 26 '13 at 04:37
  • Are you using python 3.0 or higher? I just tried this exact same thing using Python 2.7.4 and it did raise a SyntaxError on the `print` function, but then when I tried it in Python 3.3.1 it Worked perfectly fine. – KodyVanRy Oct 26 '13 at 16:12
  • I'm at the Python 2.7 level, and will likely be for a long time. – Bryce Oct 27 '13 at 01:53