Python: Nested Loop

12,358

Solution 1

>>> a = [("one","two"), ("bad","good")]
>>> print "\n".join(j for i in a for j in i)
one
two
bad
good



>>> for i in a:
...  print "\n".join(i)
... 
one
two
bad
good

Solution 2

List comprehensions and generators are only designed to be used as expressions, while printing is a statement. While you can effect what you're trying to do by doing

from __future__ import print_function
for x in a:
    [print(each) for each in x]

doing so is amazingly unpythonic, and results in the generation of a list that you don't actually need. The best thing you could do would simply be to write the nested for loops in your original example.

Solution 3

Given your example you could do something like this:

a = [("one","two"), ("bad","good")]

for x in sum(map(list, a), []):
    print x

This can, however, become quite slow once the list gets big.

The better way to do it would be like Tim Pietzcker suggested:

from itertools import chain

for x in chain(*a):
    print x

Using the star notation, *a, allows you to have n tuples in your list.

Solution 4

The print function really is superior, but here is a much more pythonic suggestion inspired by Benjamin Pollack's answer:

from __future__ import print_function
for x in a:
    print(*x, sep="\n")

Simply use * to unpack the list x as arguments to the function, and use newline separators.

Solution 5

import itertools
for item in itertools.chain(("one","two"), ("bad","good")):
    print item

will produce the desired output with just one for loop.

Share:
12,358
mRt
Author by

mRt

Updated on June 04, 2022

Comments

  • mRt
    mRt almost 2 years

    Consider this:

    >>> a = [("one","two"), ("bad","good")]
    
    >>> for i in a:
    ...     for x in i:
    ...         print x
    ... 
    one
    two
    bad
    good
    

    How can I write this code, but using a syntax like:

    for i in a:
        print [x for x in i]
    

    Obviously, This does not work, it prints:

    ['one', 'two']
    ['bad', 'good']
    

    I want the same output. Can it be done?

  • TM.
    TM. over 14 years
    This works but I'm guessing (although not positive) that in his real code he has n number of tuples, not a predefined set that he can hardcode.
  • TM.
    TM. over 14 years
    To see what I'm getting at, read tgray's answer, with the *a notation.
  • Jason Baker
    Jason Baker over 14 years
    It should also be noted that this will only work in Python 2.6 or 3
  • TM.
    TM. over 14 years
    much better off using the answer that tgray provided rather than this
  • u0b34a0f6ae
    u0b34a0f6ae over 14 years
    the print function really is awesome, however I think there is a much superior way to use it (hence my answer).
  • stephan
    stephan over 14 years
    print '\n'.join(j for k in a for j in k)