The most efficient way to iterate over a list of elements. Python 2.7
<p>I am trying to iterate over a list of elements, however the list can be massive and takes too long to execute. I am using newspaper api. The for loop I constructed is:</p>

<pre><code>for article in list_articles:
</code></pre>

<p>Each article in the list_articles are an object in the format of:</p>

<pre><code>&lt;newspaper.article.Article object at 0x1103e1250&gt;
</code></pre>

<p>I checked that some recommended using xrange or range, however that did not work in my case, giving a type error:</p>

<pre><code>TypeError: 'int' object is not iterable
</code></pre>

<p>It would be awesome if anyone can point me to the right direction or give me some idea that can efficietly increase iterating over this list.</p>

<p>The best way is to use built in functions, when possible, such as functions to split strings, join strings, group things, etc...</p>

<p>The there is the  list comprehension or <code>map</code> when possible. If you need to construct one list from another by manipulating each element, then this is it.</p>

<p>The thirst best way is the <code>for item in items</code> loop.</p>

<p><strong>ADDED</strong></p>

<p>One of the things that makes you a Python programmer, a better programmer, takes you to the next level of programming is the second thing I mentioned - list comprehension and map. Many times you iterate a list only to construct something that could be easily done with list comprehension. For example:</p>

<pre><code>new_items = []
for item in items:
    if item &gt; 3:
    print(item * 10)
    new_items.append(item * 10)
</code></pre>

<p>You could do this much better (shorter and faster and more robust) like this:</p>

<pre><code>new_items = [item * 10 for item in items if item &gt; 3]
print(items)
</code></pre>

<p>Now, the printing is a bit different from the first example, but more often than not, it doesn't matter, and even better, and also can be transformed with one line of code to what you need.</p>

python list python-2.7 loops cpython