mRt
mRt

Reputation: 1223

Python: Nested Loop

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?

Upvotes: 2

Views: 12462

Answers (8)

John La Rooy
John La Rooy

Reputation: 304137

>>> 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

Upvotes: 4

tgray
tgray

Reputation: 8966

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.

Upvotes: 7

Ofri Raviv
Ofri Raviv

Reputation: 24823

This code is straightforward and simpler than other solutions here:

for i in a:
    print '\n'.join([x for x in i])

Upvotes: 1

u0b34a0f6ae
u0b34a0f6ae

Reputation: 49793

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.

Upvotes: 3

notnoop
notnoop

Reputation: 59299

You'll need to define your own print method (or import __future__.print_function)

def pp(x): print x

for i in a:
  _ = [pp(x) for x in i]

Note the _ is used to indicate that the returned list is to be ignored.

Upvotes: 1

Benjamin Pollack
Benjamin Pollack

Reputation: 28410

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.

Upvotes: 7

Not the best, but:

for i in a:
    some_function([x for x in i])

def some_function(args):
    for o in args:
        print o

Upvotes: 0

Tim Pietzcker
Tim Pietzcker

Reputation: 336108

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

will produce the desired output with just one for loop.

Upvotes: 3

Related Questions