title: Python: Regex findall returns a list, why does trying to access the list element [0] return an error?
body: <p>Taken from the documentation, the following is a snippet showing how the regex method findall works, and confirms that it does return a list. </p>
  
  <pre><code>re.findall(r"\w+ly", text)
  ['carefully', 'quickly']
  </code></pre>
  
  <p>However the following code fragment generates an out of bounds error (<code>IndexError: list index out of range</code>)when trying to access the zeroth element of the list returned by findall. </p>
  
  <p>Relevant Code Fragment: </p>
  
  <pre><code>population = re.findall(",([0-9]*),",line)
  x = population[0]
  thelist.append([city,x])
  </code></pre>
  
  <p>Why does this happen?</p>
  
  <p>For some more background, here's how that fragment fits into my entire script: </p>
  
  <pre><code>import re
  
  thelist = list()
  with open('Raw.txt','r') as f:
      for line in f:
          if line[1].isdigit():
              city = re.findall("\"(.*?)\s*\(",line)
              population = re.findall(",([0-9]*),",line)
              x = population[0]
              thelist.append([city,x])
  
  with open('Sorted.txt','w') as g:
      for item in thelist:
          string = item[0], ', '.join(map(str, item[1:]))
          print string
  </code></pre>
  
  <p>EDIT: Read comment below for some background on why this happened. My quick fix was: </p>
  
  <pre><code>if population: 
          x = population[0]
          thelist.append([city,x])
  </code></pre>