![]() Nested loops in list comprehensions do not read like English prose. Here’s a list comprehension that does the same thing: flattened = Here’s a for loop that flattens a matrix (a list of lists): flattened = for row in matrix: What about list comprehensions with nested looping?… □ ![]() Copying the for loop line, excluding the final : (line 4).Copying the expression that we’ve been append-ing into this new list (line 5).Copying the variable assignment for our new empty list (line 3).We can copy-paste our way from a simple loop-and-append for loop by: That same code written as a comprehension: doubled_numbers = Copying the if statement line, also without the :īut what about comprehensions that don’t have a conditional clause (that if SOMETHING part at the end)? These loop-and-append for loops are even simpler than the loop-and-conditionally-append ones we’ve already covered.Ī for loop that doesn’t have an if statement: doubled_numbers = for n in numbers:.Copying the for loop line, excluding the final :.Copying the expression that we’ve been append-ing into this new list.Copying the variable assignment for our new empty list.We copy-paste from a for loop into a list comprehension by: doubled_odds = for n in numbers:ĭoubled_odds = Let’s use colors to highlight what’s going on.
0 Comments
Leave a Reply. |