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?
Given your example you could do something like this:
This can, however, become quite slow once the list gets big.
The better way to do it would be like Tim Pietzcker suggested:
Using the star notation,
*a
, allows you to have n tuples in your list.will produce the desired output with just one
for
loop.The print function really is superior, but here is a much more pythonic suggestion inspired by Benjamin Pollack's answer:
Simply use
*
to unpack the list x as arguments to the function, and use newline separators.You'll need to define your own print method (or import
__future__.print_function
)Note the
_
is used to indicate that the returned list is to be ignored.This code is straightforward and simpler than other solutions here:
Not the best, but: