35

Here's my current code:

print(list[0], list[1], list[2], list[3], list[4], sep = '\t')

I'd like to write it better. But

print('\t'.join(list))

won't work because list elements may numbers, other lists, etc., so join would complain.

max
  • 49,282
  • 56
  • 208
  • 355

3 Answers3

49
print(*list, sep='\t')

Note that you shouldn't use the word list as a variable name, since it's the name of a builtin type.

Glenn Maynard
  • 55,829
  • 10
  • 121
  • 131
  • 1
    seems like an elegant way.. but can someone explain what *list does here? – olala Jan 28 '16 at 20:19
  • 3
    @olala it's called unpacking a list. Making it into list[0], list[1], etc. like he did in the question. See for example [here](http://stackoverflow.com/questions/3480184/unpack-a-list-in-python) – Matthias Jul 04 '16 at 16:10
  • 1
    for that to work in python 2.7 don't forget to `from __future__ import print_function` as the first line in your file – ihadanny Feb 26 '17 at 14:23
  • how to assign this value to a variable ? – Happy Coder Feb 28 '21 at 07:15
36
print('\t'.join(map(str,list)))
fabrizioM
  • 46,639
  • 15
  • 102
  • 119
12
print('\t'.join([str(x) for x in list]))
cred
  • 121
  • 1
  • 2