creativz
creativz

Reputation: 10777

how to concatenate lists in python?

I'm trying to insert a String into a list.

I got this error:

TypeError: can only concatenate list (not "tuple") to list

because I tried this:

var1 = 'ThisIsAString' # My string I want to insert in the following list
file_content = open('myfile.txt').readlines()
new_line_insert = file_content[:10] + list(var1) + rss_xml[11:]
open('myfile.txt', 'w').writelines(new_line_insert)

The content of myfile.txt is saved in "file_content" as a list. I want to insert the String var1 after the 10th line, thats why I did

file_content[:10] + list(var1) + rss_xml[11:]

but the list(var1) doesn't work. How can I make this code work? Thanks!

Upvotes: 2

Views: 3356

Answers (4)

dhg
dhg

Reputation: 52681

It's important to note the "list(var1)" is trying to convert var1 to a list. Since var1 is a string, it will be something like:

>>> list('this')
['t', 'h', 'i', 's']

Or, in other words, it converts the string to a list of characters. This is different from creating a list where var1 is an element, which is most easily accomplished by putting the "[]" around the element:

>>> ['this']
['this']

Upvotes: 2

inspectorG4dget
inspectorG4dget

Reputation: 113905

file_content = file_content[:10]
file_content.append(var1)
file_content.extend(rss_xml[11:])

Upvotes: 1

Mark Byers
Mark Byers

Reputation: 837946

Lists have an insert method, so you could just use that:

file_content.insert(10, var1)

Upvotes: 3

jbochi
jbochi

Reputation: 29634

try

file_content[:10] + [var1] + rss_xml[11:]

Upvotes: 9

Related Questions