32

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
  • 45,169
  • 49
  • 189
  • 342

3 Answers3

44
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
  • 53,510
  • 10
  • 114
  • 128
  • 1
    seems like an elegant way.. but can someone explain what *list does here? – olala Jan 28 '16 at 20:19
  • 1
    @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
35
print('\t'.join(map(str,list)))
fabrizioM
  • 44,184
  • 15
  • 95
  • 115
11
print('\t'.join([str(x) for x in list]))
cred
  • 111
  • 1
  • 2