1

I am trying to print list lst using a single line of code

lst = [("A",23),("B",45),("C",88)]

print(*lst, sep="\n")

Output comes like this:

('A', 23)
('B', 45)
('C', 88)

What I am expecting is

A 23
B 45
C 88

However, this can be achieved by the following code

for i in range(len(lst)):
    print(*lst[i], sep=" ")

But I dont want to use a "for loop", rather to use * operator or any other technique to accomplish that in a single line of code

  • 1
    As you have nested `list` I think `for loop` is inevitable – Sociopath Jan 21 '20 at 06:04
  • Does this answer your question? [How to make a flat list out of list of lists?](https://stackoverflow.com/questions/952914/how-to-make-a-flat-list-out-of-list-of-lists) – MisterMiyagi Jan 21 '20 at 06:09

3 Answers3

1

You can achieve this in one line of code but it does involve a list comprehension (which you may consider a for loop):

print(*[' '.join([l[0], str(l[1])]) for l in lst], sep="\n")

Output:

A 23
B 45
C 88

Note we need to use str to convert the second value in the tuples in l into a string for join.

Nick
  • 138,499
  • 22
  • 57
  • 95
1

You could do it in one line like this:

print('\n'.join('{} {}'.format(*tup) for tup in lst))
jignatius
  • 6,304
  • 2
  • 15
  • 30
0

Another way:

print(*map(lambda x: " ".join(x), lst), sep='\n', flush=True)
Andreas
  • 8,694
  • 3
  • 14
  • 38