How to convert a list of strings into a list of integers - many things dont seem to work
<p>I have a problem. I would like to convert a list of strings with 594 elements, among them many empty, to a list of integers. I already looked up many answers here, but neither list comprehensions, neither map function seems to work. My command prompt simply says int argument must be a string or a number, not a list.</p>

<p>Here is my code:</p>

<pre><code>fname = raw_input("Enter file name: ")
if len(fname) &lt; 1 : fname = "regex_sum_317625.txt"
fh = open(fname)

import re
numlist = list()

for line in fh:
    line = line.rstrip()
    numbers = re.findall('[0-9]+', line)
    numlist.append(numbers)

print numlist
listlength = len(numlist)
print listlength

intlist = [int(nums) for nums in numlist]
print intlist
</code></pre>

<p>I tried many ways, but the problem always is that I try to do an operation on a list which is not allowed. Could you please help me, what should I do?</p>

<p>The approaches you mentioned should work, but you're not building your data correctly; you don't have a list of strings but a list of lists - <code>re.findall</code> <em>returns</em> a list:</p>

<pre><code>numbers = re.findall('[0-9]+', line)
numlist.append(numbers) # appending a list to numlist
</code></pre>

<p>You should instead <em>extend</em> <code>numlist</code> with the results of <code>re.findall</code> using the <code>extend</code> method of the list:</p>

<pre><code>numlist.extend(numbers) 
</code></pre>

<p>The <code>list.extend</code> method will</p>

<blockquote>
  <p><em>extend</em> the list by appending all the items in the given list.</p>
</blockquote>

<hr>

<p>Since you're already familiar with comprehensions, you might as well use a comprehension in place of the <code>for</code> loop:</p>

<pre><code>with open(fname) as fh:
    int_list = [int(item) for line in fh for item in re.findall('[0-9]+', line)]
</code></pre>

<p>I noticed, you did not call the <code>close</code> method of your file object <code>fh</code>. You can let Python do the cleanup for you by opening the file <em>with</em> a context manager, using the <code>with</code> statement.</p>

<p>See <a href="http://stackoverflow.com/questions/9282967/how-to-open-a-file-using-the-open-with-statement">How to open a file using the open with statement</a> to learn more about this.</p>

python list