Skip to content
Advertisement

Output tuple from a list without ‘for’

I need to output tuple from a list without for. Tell me please, how I can do it?

I have list of all permutation for some n:

l = list(itertools.permutations(range(1, int(input()) + 1)))

and I need (for example, if n = 2) :

1 2
2 1

I tried, to use sum(l, []), but I have not idea, how I can do line break.

Advertisement

Answer

What you get back from itertools.permutations is an iterator (sequence) of tuples. So if you iterate over that result, each item is a tuple. The most straightforward way you can print this data in the format you want is therefore:

for p in l:
    for x in p:
         print(x, end=' ')
    print()

But that’s not one but two for loops. Fortunately, the inner loop is unnecessary. You can unpack the tuple using the * operator so print sees it as separate arguments:

for p in l:
    print(*p)

Now, how can we get rid of the outer for loop? Well, we can use some other construct that does iteration, but isn’t a for loop. For example, we could use map.

map(lambda p: print(*p), l)

In Python 2, that would be all you needed. You’d end up with a list of None values you didn’t need, but that’s “okay.” I mean, it’s non-optimal, but it would get you the result you seek.

In Python 3, map() instantiates a map object, and nothing actually happens until you iterate over that object, typically using a for loop. One way to do it without a for loop is with any(), which consumes items from the iterator until it gets to a truthy value. The items in the map are all falsy (the lambda returns None) so any() will consume all of them. “Consuming” items from the map object will cause your lambda to be called, thereby printing each permutation.

any(map(lambda p: print(*p), l))

If you’re running this code in interactive mode, you’ll get a False printed after the values you’re looking for. That is the return value from any(). You can keep that from being printed by assigning it to a variable.

x = any(map(lambda p: print(*p), l))

Or by making sure the final expression evaluates to None, which Python won’t print:

any(map(lambda p: print(*p), l)) or None

This is pretty gross. It is not good Python code. Actually, it would be bad style in just about any language. But it does the job without a for loop…

User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement