Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

why can only concatenate list (not "str") to list

I have this code that runs without error:

result={}
for i in range(1):
    a="Bug: from the English bug — bug, bug, bug in the program".split()
    result[a[0][0:-1]]=result.get(a[0][0:-1],[]) + [' '.join(a[1:])]  # ' '.join(a[1:]) - error
print(result)

However, I do not want to add a one-element list to the .get result, but a string, like so:

result={}
for i in range(1):
    a="Bug: from the English bug — bug, bug, bug in the program".split()
    result[a[0][0:-1]]=result.get(a[0][0:-1],[]) + ' '.join(a[1:])
print(result)

But this causes an error that says TypeError: can only concatenate list (not "str") to list. Why?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

When you run your get(a[0][0:-1], []), the a[0][0:-1] or Bug key does not exist, so instead it instantiates the ‘Bug’ key in the dictionary and sets its value to the empty list []. At that point, an addition operator is treated as a concatenation and you can only concatenate lists to lists.

You can alternatively use a default value of an empty string '' instead in your get and then you can use ' '.join(a[1:]).

result = {}
for i in range(1):
    a = "Bug: from the English bug — bug, bug, bug in the program".split()
    result[a[0][0:-1]] = result.get(a[0][0:-1], '') + ' '.join(a[1:])
print(result)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading