Search code examples
pythonlistpython-2.7loopscpython

The most efficient way to iterate over a list of elements. Python 2.7


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:

for article in list_articles:

Each article in the list_articles are an object in the format of:

<newspaper.article.Article object at 0x1103e1250>

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

TypeError: 'int' object is not iterable

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.


Solution

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

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

    The thirst best way is the for item in items loop.

    ADDED

    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:

    new_items = []
    for item in items:
        if item > 3:
        print(item * 10)
        new_items.append(item * 10)
    

    You could do this much better (shorter and faster and more robust) like this:

    new_items = [item * 10 for item in items if item > 3]
    print(items)
    

    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.