Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to concatenate lists in python?

Tags:

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!

like image 644
creativz Avatar asked Nov 21 '25 04:11

creativz


2 Answers

try

file_content[:10] + [var1] + rss_xml[11:]
like image 199
jbochi Avatar answered Nov 23 '25 17:11

jbochi


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

file_content.insert(10, var1)
like image 26
Mark Byers Avatar answered Nov 23 '25 16:11

Mark Byers



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!