What are the advantages of list comprehension in Python compared to loops? Will performance be higher?

Source: Internet
Author: User
List comprehension in Python is typically used to compute another list from one list, functionally, as a map/filter, or through loops. Previously looked up some related information, some people say that the list derivation is only the grammatical sugar, also has said that the list derivation is more efficient than the circulation and the Map/filter (only gave a test result, no correlation analysis), other valuable information did not find ... This is one of the questions asked by an interviewer, I think it is necessary to find out, so I would like to know to ask you the great God.
In the design philosophy of Python, there is the phrase "there should be one--and preferably only one--obvious way to do it." If there is no difference between the list derivation and the loop and the Map/filter implementation , should it not exist? Of course, the philosophy of Python also has "Beautiful is better than ugly.", it seems that it may be just for the sake of good looks ...

Reply content:

First of all, the map and list derivation efficiency is indeed higher than the loop,

Let's start with the list derivation, below is my test results in Ipython (test environment Python 2.7.10):

>>> long_list = range(1000)>>> a = []>>> %timeit for i in long_list: a.append(i+1)10000 loops, best of 3: 100 µs per loop>>> %timeit [i+1 for i in long_list]10000 loops, best of 3: 43.3 µs per loop
A little more efficient, to see the DIS module.

Python does not like FP, and Map/filter is inert, list comprehension is not.

Loops are much lower than list comprehension and difficult to understand. Compare: "Multiply all the elements in this list by two" and "Create an empty list B, add the result to the end of B by multiplying each element in the listing a by two."

PS: For every use case that can be implemented in a variety of ways, I can basically identify an optimal approach.
  • Related Article

    Contact Us

    The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

    If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

    A Free Trial That Lets You Build Big!

    Start building with 50+ products and up to 12 months usage for Elastic Compute Service

    • Sales Support

      1 on 1 presale consultation

    • After-Sales Support

      24/7 Technical Support 6 Free Tickets per Quarter Faster Response

    • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.