"list comprehension" in python

Home Forums Python Programming "list comprehension" in python

Viewing 1 post (of 1 total)
  • Author
    Posts
  • #2057 Reply
    Humble
    Keymaster

    List comprehensions apply an arbitrary expression to items in an iterable rather than applying function.

    In previous posts I wrote map() , filter()..etc do the same job.. How-ever if you notice, the list comprehension perform “expressions” in a sequence and “map(),”filter()”..etc perform functions on a sequence.. It is important to understand this difference.

    For ex: below are examples for list comprehensions.

    >>> [2 * x for x in range(1,10)]
    [2, 4, 6, 8, 10, 12, 14, 16, 18]
    >>> 
    
    >>> [x ** 2 for x in range(10) if x % 2 == 0]
    [0, 4, 16, 36, 64]
    
    >>> s= [10,100,20]
    >>> [2 * x for x in s]
    [20, 200, 40]
    >>> 
    
    
    
    Though list comprehensions construct lists, they can iterate over any sequence:
    
    When compared to map(), list comprehension has performance advantages.. That said, when you perform list comprehensions , functions are not in picture which basically reduce the stack performance overhead compared to what map() has.. At the same time I would like to point that map() is better than simple "for" loop coding. 
    
    
    
Viewing 1 post (of 1 total)
Reply To: "list comprehension" in python
Your information: