James
James

Reputation: 63

Python Nested List

Hi I have to print each element in nested list using nested loops, but the code i wrote prints each element per line, but i need it to print all the items in the inner list per line.

new_grid=[['(a)', '(b)'], ['(c)','(d)'], ['(e)', '(f)']]
def print_newgrid():
    ''' 
    when printed it should look like:
    (a)(b)
    (c)(d)
    (e)(f)
    '''
    for i in new_grid:
        for j in i:
            print(j)

This prints each element per line, instead of two. Any help is appreciated thanks

Upvotes: 1

Views: 86

Answers (2)

Elmex80s
Elmex80s

Reputation: 3504

This

print "\n".join([l[0] + l[1] for l in new_grid])

Will give

(a)(b)
(c)(d)
(e)(f)

Upvotes: 0

mechanical_meat
mechanical_meat

Reputation: 169264

Since you say you need to use nested lists, try:

>>> for i in new_grid:
...   for j in i:
...     print(j,end="")
...   print("")
...
(a)(b)
(c)(d)
(e)(f)

Or more simply:

>>> for i in new_grid:
...   print("".join(i))
...
(a)(b)
(c)(d)
(e)(f)

Since

Upvotes: 2

Related Questions