Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pythonic way to print 2D list -- Python

I have a 2D list of characters in this fashion:

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

What's the most pythonic way to print the list as a whole block? I.e. no commas or brackets:

123
456
789
like image 310
Graviton Avatar asked Jul 11 '17 07:07

Graviton


People also ask

How do you traverse a 2d array in Python?

Traversing in a 2D array in python can be done by using a for loop. We can iterate through the outer array first and then at each element of the outer array, we have another array which is our inner array containing the elements. So for each inner array, we run a loop to traverse its elements.

How do you print a list in Python nicely?

Pass a list as an input to the print() function in Python. Use the asterisk operator * in front of the list to “unpack” the list into the print function. Use the sep argument to define how to separate two list elements visually.


2 Answers

There are a lot of ways. Probably a str.join of a mapping of str.joins:

>>> a = [['1','2','3'],
...          ['4','5','6'],
...          ['7','8','9']]
>>> print('\n'.join(map(''.join, a)))
123
456
789
>>>
like image 58
juanpa.arrivillaga Avatar answered Oct 23 '22 22:10

juanpa.arrivillaga


Best way in my opinion would be to use print function. With print function you won't require any type of joining and conversion(if all the objects are not strings).

>>> a = [['1','2','3'],
...      ['4', 5, 6],   # Contains integers as well.
...      ['7','8','9']]
...

>>> for x in a:
...     print(*x, sep='')
...
...
123
456
789

If you're on Python 2 then print function can be imported using from __future__ import print_function.

like image 32
Ashwini Chaudhary Avatar answered Oct 23 '22 20:10

Ashwini Chaudhary