0

How do I print, separated by tabs, the values of all the strings in a list without prior knowledge of the number of strings in a list?

If I knew that the list has just 3 elements, I could do something like this:

l = ['A', 'B', 'C']
print "\t".join([l[0], l[1], l[2]])

And I would obtain

A       B       C

But I have no idea of how to do it for n strings in a automated way

3 Answers3

3

l = ['A','B','C']

joined_string = "\t".join(l)

print joined_string

Community
  • 1
  • 1
2
l = ['A', 'B', 'C']
print "\t".join(l)

Now just in case your lists contains several lists within them:

import itertools

l = ['A', 'B', 'C', ['d', 'D']]
foo = [item for item in itertools.chain(*l)]
print "\t".join(foo)
Eduard
  • 666
  • 1
  • 8
  • 25
  • omg now Im feeling like a bit stupid, it was so easy... Thank you very much – Álvaro Méndez Civieta May 18 '17 at 10:40
  • There's really nothing stupid in something that we do not know. Reading the docs would definitely help a lot. Glad to help you. – Eduard May 18 '17 at 10:43
  • 1
    Why do you use list comprehension to create a list identical to the original list? Just use `foo = "\t".join(l)` instead. – Szabolcs May 18 '17 at 11:10
  • I was planning to expand this answer that a list that contains collections within them may require a different approach. Edited – Eduard May 19 '17 at 02:17
  • 1
    @Eduard An exception will occur if the main list contains nested lists deeper than 1 level. Like: `l = ['A', 'B', ['C', 'D', ['E']]]` will cause `TypeError: sequence item 4: expected string, list found`. – Szabolcs May 19 '17 at 08:34
  • That is true indeed, after a few search, this would be the best solution. http://stackoverflow.com/questions/2158395/flatten-an-irregular-list-of-lists – Eduard May 19 '17 at 09:10
1

Try:

>>> l = ['A', 'B', 'C']
>>> foo = "\t".join(l)
>>> print foo

Will output:

A   B   C
Szabolcs
  • 3,990
  • 18
  • 38