-2

words_list = ['who', 'got', '\n', 'inside', 'your', '\n', 'mind', 'baby']

I have this list of words stored as a list element. I wanted to use the elements as contents of the print function. Ex.

print(words_list[0] + words_list[1] + words_list[2]...words_list[n])

My desired output would be:

who got 
inside your
mind baby
Rayleigh
  • 20
  • 5

1 Answers1

1

In Python 3 you can do:

print(*words_list)

because print is just a function and the * operator in this context will unpack elements of your list and put them as positional arguments of the function call.

In older versions you'd need to concatenate (join) elements of the array first, possibly converting them to strings, if they are not strings already. This can be done like this:

print ' '.join([str(w) for w in words_list])

or, more succinctly, using generator expression instead of list comprehension:

print ' '.join(str(w) for w in words_list)

Yet another alternative is to use the map function, which results in even shorter code:

print ' '.join(map(str, words_list))

However, if you are on Python 2.6+ but not on Python 3, you can get print as a function by importing it from the future:

from __future__ import print_function
print(*words_list)
piokuc
  • 25,594
  • 11
  • 72
  • 102
  • That's not exactly correct. You can use `print` as a function in Python 2.7 (maybe older versions, too, but these should not be used since years). Just import the correct future, which is a good idea anyway. – too honest for this site Mar 16 '18 at 12:06
  • Why use a list comprehension? print(' '.join(word_list)) would produce the same output. – uwain12345 Mar 16 '18 at 13:19