planetp
planetp

Reputation: 16085

How can I combine these calls to print()?

In my program I need to output a list of points in a grid (tuples of row and column). However, sometimes rows and columns need to be swapped. Currently, I do it like this:

 if swapped:
    for col, row in points:
        print(row, col)
 else:
    for row, col in points:
        print(row, col)

Is there any way I can do it with a single call to print()?.

Upvotes: 3

Views: 72

Answers (5)

The easiest and most simple way to do a swap in python is the following:

s1, s2 = s2, s1

In your care the code could look like this

for col, row in points:
  if swapped:
    col, row = row, col
  print(row, col)

Upvotes: 1

Devesh Kumar Singh
Devesh Kumar Singh

Reputation: 20490

This should work as well


points = [(1,2), (3,4)]
swapped = True
for col, row in points:
    print((row, col) if swapped else (col, row))
#(2, 1)
#(4, 3)

Another example is

points = [(1,2.5), ('x',4)]
swapped = False
for col, row in points:
    print((row, col) if swapped else (col, row))
#(1, 2.5)
#('x', 4)

Upvotes: 0

Chetan Ameta
Chetan Ameta

Reputation: 7896

have a look on below solution, swap the variable:

for col, row in points:
    if swapped:
        row, col = col, row
    print(row, col)

Upvotes: 0

Netwave
Netwave

Reputation: 42718

So, swap them:

for col, row in points:
    if swapped:
        col, row = row, col
    print(col, row)

Upvotes: 3

U13-Forward
U13-Forward

Reputation: 71580

You mean?

for col, row in points:
    print(row + ' ' + col if swapped else col + ' ' + row)

Output would be as expected with just using one print.

Upvotes: 3

Related Questions