Follow Techotopia on Twitter

On-line Guides
All Guides
eBook Store
iOS / Android
Linux for Beginners
Office Productivity
Linux Installation
Linux Security
Linux Utilities
Linux Virtualization
Linux Kernel
System/Network Admin
Programming
Scripting Languages
Development Tools
Web Development
GUI Toolkits/Desktop
Databases
Mail Systems
openSolaris
Eclipse Documentation
Techotopia.com
Virtuatopia.com
Answertopia.com

How To Guides
Virtualization
General System Admin
Linux Security
Linux Filesystems
Web Servers
Graphics & Desktop
PC Hardware
Windows
Problem Solutions
Privacy Policy

  




 

 

7.1.4 List Comprehensions

List comprehensions provide a concise way to create lists without resorting to use of map(), filter() and/or lambda. The resulting list definition tends often to be clearer than lists built using those constructs. Each list comprehension consists of an expression followed by a for clause, then zero or more for or if clauses. The result will be a list resulting from evaluating the expression in the context of the for and if clauses which follow it. If the expression would evaluate to a tuple, it must be parenthesized.

    >>> freshfruit = ['  banana', '  loganberry ', 'plum  ']
    >>> [weapon.strip() for weapon in freshfruit]
    ['banana', 'loganberry', 'plum']
    >>> vec = [2, 4, 6]
    >>> [3*x for x in vec]
    [6, 12, 18]
    >>> [3*x for x in vec if x > 3]
    [12, 18]
    >>> [3*x for x in vec if x < 2]
    []
    >>> [[x,x**2] for x in vec]
    [[2, 4], [4, 16], [6, 36]]
    >>> [x, x**2 for x in vec]	# error - need () for tuples
      File "<stdin>", line 1, in ?
        [x, x**2 for x in vec]
                   ^
    SyntaxError: invalid syntax
    >>> [(x, x**2) for x in vec]
    [(2, 4), (4, 16), (6, 36)]
    >>> vec1 = [2, 4, 6]
    >>> vec2 = [4, 3, -9]
    >>> [x*y for x in vec1 for y in vec2]
    [8, 6, -18, 16, 12, -36, 24, 18, -54]
    >>> [x+y for x in vec1 for y in vec2]
    [6, 5, -7, 8, 7, -5, 10, 9, -3]
    >>> [vec1[i]*vec2[i] for i in range(len(vec1))]
    [8, 12, -54]

To make list comprehensions match the behavior of for loops, assignments to the loop variable remain visible outside of the comprehension:

    >>> x = 100             # this gets overwritten
    >>> [x**3 for x in range(5)]
    [0, 1, 8, 27, 64]
    >>> x
    4                       # the final value for range(5)
    >>

 
 
  Published under the terms of the Python License Design by Interspire