10

I am using the latest Python 3

letters = ['a', 'b', 'c', 'd', 'e']
letters[:3]
print((letters)[:3])
letters[3:]
print((letters)[3:])
print("Here is the whole thing :" + letters)

Error:

Traceback (most recent call last):
  File "C:/Users/Computer/Desktop/Testing.py", line 6, in <module>
    print("Here is the whole thing :" + letters)
TypeError: Can't convert 'list' object to str implicitly

When fixing, please explain how it works :) i dont want to just copy a fixed line

Anshul Goyal
  • 73,278
  • 37
  • 149
  • 186
Excetera
  • 125
  • 1
  • 2
  • 6

3 Answers3

16

As it currently stands, you are trying to concatenate a string with a list in your final print statement, which will throw TypeError.

Instead, alter your last print statement to one of the following:

print("Here is the whole thing :" + ' '.join(letters)) #create a string from elements
print("Here is the whole thing :" + str(letters)) #cast list to string
Anshul Goyal
  • 73,278
  • 37
  • 149
  • 186
3
print("Here is the whole thing : " + str(letters))

You have to cast your List-object to String first.

Leistungsabfall
  • 6,368
  • 7
  • 33
  • 41
1

In addition to the str(letters) method, you can just pass the list as an independent parameter to print(). From the doc string:

>>> print(print.__doc__)
print(value, ..., sep=' ', end='\n', file=sys.stdout, flush=False)

Prints the values to a stream, or to sys.stdout by default.

So multiple values can be passed to print() which will print them in sequence, separated by the value of sep (' ' by default):

>>> print("Here is the whole thing :", letters)
Here is the whole thing : ['a', 'b', 'c', 'd', 'e']
>>> print("Here is the whole thing :", letters, sep='')   # strictly your output without spaces
Here is the whole thing :['a', 'b', 'c', 'd', 'e']

Or you can use string formatting:

>>> letters = ['a', 'b', 'c', 'd', 'e']
>>> print("Here is the whole thing : {}".format(letters))
Here is the whole thing : ['a', 'b', 'c', 'd', 'e']

Or string interpolation:

>>> print("Here is the whole thing : %s" % letters)
Here is the whole thing : ['a', 'b', 'c', 'd', 'e']

These methods are generally preferred over string concatenation with the + operator, although it's mostly a matter of personal taste.

mhawke
  • 84,695
  • 9
  • 117
  • 138