0

I can print nested lists line by line by using for loop and " ".join() mapping each int in the nested list to a str with map().

Example:

>>> ys = [[1, 2, 3], [4, 5, 6], [7, 8, 9, 10]]
>>> for xs in ys:
...     print(" ".join(map(str, xs)))
... 
1 2 3
4 5 6
7 8 9 10

But I am trying to figure out how to do this again without for loops that can support arbitrary lengths of inner lists. Any suggestions?

4
  • 1
    Is there any particular reason you're avoiding a for loop? Commented Feb 7, 2017 at 19:42
  • Not really... I just wanted to practice solving a problem with different approaches. Commented Feb 7, 2017 at 19:43
  • So, are you saying that the lists within lists could go deeper? Like you could have a list within a list within a list? Commented Feb 7, 2017 at 19:44
  • I didn't think of that case and that could get messy and I don't know how I would enter each row.. so for the sake of practice I'll just assume that its just a list within a list. Commented Feb 7, 2017 at 19:46

3 Answers 3

3

Since the depth is known and fixed, you can nest 2 map statements in a one-liner, using lambda to avoid comprehension (which would involve a for loop)

ys = [[1, 2, 3], [4, 5, 6], [7, 8, 9, 10]]
print("\n".join(map(lambda xs : " ".join(map(str, xs)),ys)))

no for loop, at least none visible.

From a performance point of view, map performs a loop but problably compiled, so it is faster. On the other hand, join needs to know the size of the input so a list is created out of the iterable anyway, and join + list comprehension is then faster (not in Python 2 where map returns a list). In a word: use timeit to determine the fastest variant with your context.

Sign up to request clarification or add additional context in comments.

3 Comments

Thanks! That would make sense to use 2 map statements. I didn't think of that method!
The performance considerations when thinking about map vs for-loop or map vs comprehension are not as straight-forward. See stackoverflow.com/a/39046254/5014455 There is also the added complication that built-in functions generally are mapped faster using map, compared to an equivalent list comprehension, but user-defined functions show the opposite pattern (comprehensions map faster than map).
@juanpa.arrivillaga timeit will be the only judge :)
1
ys = [[1, 2, 3], [4, 5, 6], [7, 8, 9, 10]]
print "\n".join( [" ".join(map(str,subList)) for subList in ys] )

Code Explained:

[" ".join(map(str,subList)) for subList in ys]

This created a list of string with each value of each list combined with a space.

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

"\n".join() is pretty self explantory after that.

EDIT:

Updated to use lambda instead of for.

ys = [[1, 2, 3], [4, 5, 6], [7, 8, 9, 10]]
print "\n".join( map(lambda x: " ".join(map(str,x)),ys) )

4 Comments

Yeah that would make sense except for the for. Thanks though! Interesting solution.
@pewnienewbie, I updated this to use lambda instead of for. Not sure if this will be okay.
@Michael, yeah that would work! That's actually what Jean-Francois did :)
@Michael: Quick question, why does "\n"join() print with a new space when print is written before it and if there wasn't a print it would of just been '1 2 3\n4 5 6\n7 8 9 10'. Does print take \n as an enter?
1

As a recursive function for any length/depth of lists:

def recursive_print_list(param):
    while len(param) > 0:
        if isinstance(param[0], list):
            recursive_print_list(param[0])
            print("")
            param = param[1:]
        else:
            print(param[0], '', end='')
            param = param[1:]

Worth noting the other two answers won't work for depth > 2. This will. It also relies on print()s implicit conversion to string, and will therefore work on any mixed input so long as you can print(element) all elements.


Original Answer:

xs = ys[:]  # copy the original list, as this method is destructive
while True:
    try:
        print " ".join(map(str, xs[0]))
        xs = xs[1:]
    except IndexError:
        break

will work for arbitrary nested lists of ints.

You could use the same method to avoid the map call as well: Python 3:

xs = ys[:]
while True:
    if len(xs) == 0:
        break
    subl = xs[0][:]
    while True:
        try:
            print(subl[0], ' ', sep='', end='')
            subl = subl[1:]
        except IndexError:
            print("")
            break
    xs = xs[1:]

Python 2.7:

xs = ys[:]
while True:
    if len(xs) == 0:
        break
    subl = xs[0][:]
    while True:
        try:
            print subl[0],
            subl = subl[1:]
        except IndexError:
            print ""
            break
    xs = xs[1:]

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.