User Tools

Site Tools


python3:list_comprehensions

Differences

This shows you the differences between two versions of the page.

Link to this comparison view

Both sides previous revision Previous revision
python3:list_comprehensions [2019/05/07 14:52]
jguerin Added note about tests/storage and generators.
python3:list_comprehensions [2019/05/07 16:19] (current)
jguerin Moved the multiple loop example, switched x*2 to abs(x) in list example.
Line 20: Line 20:
 [0, 1, 4, 9, 16, 25, 36, 49, 64, 81] [0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
 </code> </code>
 +
 +
 +
 +===== Example Functionality =====
  
 ==== Multiple Loops ==== ==== Multiple Loops ====
-Note that this basic syntax is easily extended to multiple loops and variables: 
 <code python> <code python>
 >>> [(x**2, y**2) for x in range(3) for y in range(3)] >>> [(x**2, y**2) for x in range(3) for y in range(3)]
Line 28: Line 31:
 </code> </code>
  
-===== Examples ===== +====Conditionals====
-Conditionals:+
 <code python> <code python>
 >>> [(x, y) for x in [1,2,3] for y in [3,1,4] if x != y] >>> [(x, y) for x in [1,2,3] for y in [3,1,4] if x != y]
Line 35: Line 37:
 </code> </code>
  
-Repetitions:+====Repetitions====
 <code python> <code python>
 >>> [i for i in range(1, 5) for j in range(i)] >>> [i for i in range(1, 5) for j in range(i)]
Line 41: Line 43:
 </code> </code>
  
-Processing non-range() iterables:+====Processing non-range() iterables====
 <code python> <code python>
 >>> vec = [-4, -2, 0, 2, 4] >>> vec = [-4, -2, 0, 2, 4]
->>> [x*2 for x in vec] +>>> [abs(xfor x in vec] 
-[-8-4, 0, 4, 8]+[4, 2, 0, 2, 4
 +</code> 
 + 
 + 
 +====Creating a double list==== 
 +<code python> 
 +>>> n = 3 
 +>>> [[i for i in range(j*nj*n+n)] for j in range(n)] 
 +[[0, 1, 2], [3, 4, 5], [6, 7, 8]]
 </code> </code>
  
-Flattening a double list:+====Flattening a double list====
 <code python> <code python>
 >>> vec = [[1,2,3], [4,5,6], [7,8,9]] >>> vec = [[1,2,3], [4,5,6], [7,8,9]]
python3/list_comprehensions.txt · Last modified: 2019/05/07 16:19 by jguerin