1

Given a list like so:

[[1,2,3],[4,5,6],[7,8,9]]

I'm trying to get my output to look like this, with using only a list comprehension:

1 2 3
4 5 6
7 8 9

Right now I have this:

[print(x,end="") for row in myList for x in row]

This only outputs:

1 2 3 4 5 6 7 8 9

Is there a way to have it break to a new line after it processes each inner list?

Kmat
  • 401
  • 1
  • 6
  • 14
  • 2
    If you're not building a list, why are you trying to use a list comprehension? Why not a set or dictionary comprehension, if we're building dummy objects only to discard them? – DSM Feb 25 '15 at 04:16
  • 2
    `print()` is a function with side-effects, don't use it with comprehensions: [Is it Pythonic to use list comprehensions for just side effects?](http://stackoverflow.com/questions/5753597/is-it-pythonic-to-use-list-comprehensions-for-just-side-effects) – Ashwini Chaudhary Feb 25 '15 at 04:20

5 Answers5

2

You could do like the below.

>>> l = [[1,2,3],[4,5,6],[7,8,9]]
>>> for i in l:
        print(' '.join(map(str, i)))


1 2 3
4 5 6
7 8 9
Avinash Raj
  • 172,303
  • 28
  • 230
  • 274
1

You can do as follows:

print("\n".join(" ".join(map(str, x)) for x in mylist))

Gives:

1 2 3
4 5 6
7 8 9
Marcin
  • 215,873
  • 14
  • 235
  • 294
1
>>> l = [[1,2,3],[4,5,6],[7,8,9]]
>>> for line in l:
        print(*line)
1 2 3
4 5 6
7 8 9

A good explanation of the star in this answer. tl;dr version: if line is [1, 2, 3], print(*line) is equivalent to print(1, 2, 3), which is distinct from print(line) which is print([1, 2, 3]).

Community
  • 1
  • 1
Andrew Magee
  • 6,506
  • 4
  • 35
  • 58
1

I agree with Ashwini Chaudhary that using list comprehension to print is probably never the "right thing to do".

Marcin's answer is probably the best one-liner and Andrew's wins for readability.

For the sake of answering the question that was asked...

>>> from __future__ import print_function # python2.x only
>>> list = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
>>> [print(*x, sep=' ') for x in list]
1 2 3
4 5 6
7 8 9
[None, None, None]
Enrico
  • 10,377
  • 8
  • 44
  • 55
0

Try this: print("\n".join([' '.join([str(val) for val in list]) for list in my_list]))

In [1]:  my_list = [[1,2,3],[4,5,6],[7,8,9]]

In [2]: print("\n".join([' '.join([str(val) for val in list]) for list in my_list]))

1 2 3
4 5 6
7 8 9
Shaikhul
  • 642
  • 5
  • 8