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?

2
  • 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? Commented Feb 25, 2015 at 4: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? Commented Feb 25, 2015 at 4:20

5 Answers 5

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
Sign up to request clarification or add additional context in comments.

1 Comment

Why not print(*i, sep=' ')?
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

Comments

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]).

Comments

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]

Comments

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.